美文网首页
LeetCode 1309. Decrypt String fr

LeetCode 1309. Decrypt String fr

作者: LiNGYu_NiverSe | 来源:发表于2020-12-08 00:06 被阅读0次

    Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:
    给定由数字('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循环一次检查每个1或2个字符。第二种解决方案使用字典将数字替换为字符。

    相关文章

      网友评论

          本文标题:LeetCode 1309. Decrypt String fr

          本文链接:https://www.haomeiwen.com/subject/ctgxgktx.html