算法:动态规划
91.解码方法
一条包含字母 A-Z 的消息通过以下方式进行了编码:
‘A’ -> 1
‘B’ -> 2
…
‘Z’ -> 26
给定一个只包含数字的非空字符串,请计算解码方法的总数。
示例 1:
输入: “12”
输出: 2
解释: 它可以解码为 “AB”(1 2)或者 “L”(12)。
示例 2:
输入: “226”
输出: 3
解释: 它可以解码为 “BZ” (2 26), “VF” (22 6), 或者 “BBF” (2 2 6) 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/decode-ways
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
python写法
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = [int(item) for item in s]
nums = [0,1]
for i in range(len(s)):
x = s[i]
tmp = 0
if x>=1 and x<=9:
tmp+=nums[1]
if i>=1:
x = s[i-1]*10+s[i]
if 10<=x<=26:
tmp+=nums[0]
nums[0]=nums[1]
nums[1]=tmp
return nums[1]