有一种将字母编码成数字的方式:'a'->1, 'b->2', ... , 'z->26'。
现在给一串数字,返回有多少种可能的译码结果
数据范围:字符串长度满足
进阶:空间复杂度 ,时间复杂度
有一种将字母编码成数字的方式:'a'->1, 'b->2', ... , 'z->26'。
"12"
2
2种可能的译码结果(”ab” 或”l”)
"31717126241541717"
192
192种可能的译码结果
class Solution: def solve(self , nums: str) -> int: # write code here dp = [0] * (len(nums)+1) dp[-1] = 1 if nums[0]!='0': dp[0] = 1 for i in range(1, len(nums)): if nums[i]!='0': dp[i] = dp[i-1] num = int(nums[i-1:i+1]) if num<27 and num>9: dp[i] += dp[i-2] return dp[-2]
结合1楼和1楼的评论,如果是10和20结尾,应该返回a的数量,比如110,120只有1种翻译,而不是2种。
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 解码 # @param nums string字符串 数字串 # @return int整型 # class Solution: def solve(self , nums: str) -> int: # write code here if not nums or nums== '0': return 0 a = b = 1 # a f(i-2) b f(i-1) for i in range(1,len(nums)): tmp = nums[i-1:i+1] if tmp == '00'or (tmp >= "30" and tmp[-1] == "0"): # 如果有00连续则无法翻译 返回0 return 0 # 有0的如 10 20看成可翻译的一个数,而不是两个数的情况 # c = a + b if '11' <= tmp <= '26' and '0' not in tmp else b if tmp=='10' or tmp=='20': c = a else: c = a + b if '11' <= tmp <= '26' else b a, b = b, c return b
class Solution: def solve(self , nums: str) -> int: # write code here n = len(nums) dp = [0] * (n+1) dp[0] = 1 dp[1] = 1 if nums[0] != '0' else 0 print(dp) for i in range(2, n+1): if nums[i-1] != '0': dp[i] += dp[i-1] if '10'<= nums[i-2:i] <= '26': dp[i] += dp[i-2] return dp[n]
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 解码 # @param nums string字符串 数字串 # @return int整型 # class Solution: def solve(self , nums: str) -> int: if len(nums) == 0&nbs***bsp;nums[0] == '0': return 0 ret, s1, s2 = 1, 1, 1 last = 3 for i in nums: s2, s1 = s1, ret if int(i) == 0: if last > 2&nbs***bsp;last == 0: return 0 ret = s2 elif last == 0: ret = s2 elif last * 10 + int(i) > 26: ret = s1 else: ret = s1 + s2 last = int(i) return ret
class Solution: def solve(self , nums: str) -> int: # write code here if not nums&nbs***bsp;nums== '0': return 0 a = b = 1 # a f(i-2) b f(i-1) for i in range(1,len(nums)): tmp = nums[i-1:i+1] if tmp == '00': # 如果有00连续则无法翻译 返回0 return 0 # 有0的如 10 20看成可翻译的一个数,而不是两个数的情况 # c = a + b if '11' <= tmp <= '26' and '0' not in tmp else b c = a + b if '11' <= tmp <= '26' and tmp != '20' else b a, b = b, c return b有条件的青蛙跳, 不仅是11 到 26 还要对0进行处理