问题描述:
A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1 'B' -> 2 ... 'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12"
, it could be decoded as "AB"
(1 2) or "L"
(12).
The number of ways decoding "12"
is 2.
思路:
这道题也是动态规划的思想。设置一个数组a,a[i]表示第i个位置可划分数量。
这道题里'0'是个很让人烦恼的元素(其实主要考虑的就是第i个位置为0时的划分情况)
‘110’‘1212’‘012’‘340’诸如此类的测试案例。
设置一个sum变量,计算当前s[i]与s[i-1]的十进制的和(s是给的数字字符串)。sum = s[i-1]*10 +s[i]
分几种情况讨论。
sum = 0:说明字符串中有两个连续的0,可直接返回0
sum 在(10,26]之中,且不为10,20这种特殊情况。则a[i] = a[i-1]+a[i-2]
sum = [1,10] or sum =20说明s[i]与s[i-1]中有一个为0,那么a[i] = a[i-2]
(如340这个例子,‘40’必须绑定在一起,所以需要往前两个位置,与'3'同)
sum = 40,50,60这类数字,也就是 sum %10 =0的时候,也直接返回0
sum = 其他数字时,也就是只能一个一个数字前进,那么划分数量与前一个位置相同。
感觉这么写还是挺烦的。
class Solution:
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
l = len(s)
if s == '' or s == '0' * l or s[0] == '0':
return 0
elif l == 1:
return 1
else:
a = [0] * (l+1)
a[0] = 1
a[1] = 1
for i in range(1,l):
sum = int(s[i-1]) * 10 + int(s[i])
if sum == 0 :
return 0
elif sum <= 26 and sum >10 and sum != 20:
a[i+1] = a[i] + a[i-1]
elif sum <=10 or sum == 20:
a[i+1] = a[i-1]
elif sum%10 != 0:
a[i+1] = a[i]
else:
return 0
return a[l]