描述
Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:
- 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.
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"
Note:
- 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.
解析
根据题意,将数字和 # 结合的字符串转换成字母字符串,先根据题意,把转换规则存在字典对象 d 中,然后针对输入的特点,从后往前遍历 s ,只要不是 # ,那么直接通过 d 转换成字母,如果是 # ,则连同之前的两个数字组合而成的字符串一起进行转换,最后得到的字符串再反转一下,就是最终结果。
解答
class Solution(object):
def freqAlphabets(self, s):
"""
:type s: str
:rtype: str
"""
d = {'1': 'a',
'10#': 'j',
'11#': 'k',
'12#': 'l',
'13#': 'm',
'14#': 'n',
'15#': 'o',
'16#': 'p',
'17#': 'q',
'18#': 'r',
'19#': 's',
'2': 'b',
'20#': 't',
'21#': 'u',
'22#': 'v',
'23#': 'w',
'24#': 'x',
'25#': 'y',
'26#': 'z',
'3': 'c',
'4': 'd',
'5': 'e',
'6': 'f',
'7': 'g',
'8': 'h',
'9': 'i'}
res = ""
i=len(s)-1
while i>=0:
if s[i]!='#':
res += d[s[i]]
i -= 1
else :
res += d[s[i-2:i+1]]
i -= 3
return res[::-1]
运行结果
Runtime: 16 ms, faster than 88.89% of Python online submissions for Decrypt String from Alphabet to Integer Mapping.
Memory Usage: 13.5 MB, less than 75.40% of Python online submissions for Decrypt String from Alphabet to Integer Mapping.
原题链接:leetcode.com/problems/de…
您的支持是我最大的动力