LeetCode 1309. Decrypt String from Alphabet to Integer Mapping 將字符串從字母解密為整數(shù)映射 (Easy))

Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:
給定由數(shù)字('0'-'9')和'#'組成的字符串s。我們希望將s映射為英文小寫字符,如下所示:

Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
Return the string formed after mapping.
字符('a'至'i')分別由('1'至'9')表示。
字符('j'至'z')分別由('10#'至'26#')表示。
返回映射后形成的字符串。

It's guaranteed that a unique mapping will always exist.
確保映射將始終唯一。

Example 1:

Input: s = "10#11#12"
Output: "jkab"
Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".

Example 2:
Input: s = "1326#"
Output:"acz"

Example 3:
Input: s = "25#"
Output: "y"

Example 4:
Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#"
Output: "abcdefghijklmnopqrstuvwxyz"

Constraints:

  • 1 <= s.length <= 1000
  • s[i] only contains digits letters ('0'-'9') and '#' letter.
  • s will be valid string such that mapping is always possible.

Solution:

#solution1
class Solution:
    def freqAlphabets(self, s: str) -> str:
        ref = "abcdefghijklmnopqrstuvwxyz"
        res = []
        i = 0
        while i < len(s):
            curr = s[i]
            if i + 2 < len(s) and s[i+2] == "#":
                curr = s[i:i+2]
                res.append(ref[int(curr)-1])
                i += 2
            else:
                res.append(ref[int(curr)-1])
            i += 1
        return "".join(res)
#solution2
class Solution:
    def freqAlphabets(self, s: str) -> str:
        lookup1 = {'10#':'j','11#':'k','12#':'l','13#':'m','14#':'n','15#':'o',
                   '16#':'p','17#':'q','18#':'r','19#':'s','20#':'t','21#':'u',
                   '22#':'v','23#':'w','24#':'x','25#':'y','26#':'z'}
        lookup2 = {'1':'a','2':'b','3':'c','4':'d','5':'e','6':'f',
                   '7':'g','8':'h','9':'i'}
            
        for key, value in lookup1.items():
            s = s.replace(key, value)
        for key, value in lookup2.items():
            s = s.replace(key, value)
        return s

The first solution uses while loop to check each 1 or 2 characters once a time. The second solution uses dictionary to replace numbers to characters.
第一種解決方案使用while循環(huán)一次檢查每個1或2個字符。第二種解決方案使用字典將數(shù)字替換為字符。

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容