题目链接:https://leetcode.com/problems/decode-ways/description/
一开始就想到了和前边的数相关,但是没有细想,导致出错。后来在纸上特意把前边的数给圈出来了,灵感突现。
举个例子:222的解码方式为3种,22的解码方式为2种,2的解码方式为1种。即(222)解码方式=(22 2)方式+(2 22)方式
1272的解码方式为2种,127的解码方式为2种,12的的解码方式为2种,即(1272)的解码方式=(127)的解码方式。该例种不在加12的解码方式,是因为此时后两位数是72,不在编码范围之内,无论12的编码方式有多少种,配合72都是无法解码的,故只能等于(127)的解码方式
通过以上发现,前n个数的编码种数和前(n-1)、(n-2)个数的解码种数有关。此外还要特别考虑0。
代码如下:
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
length=len(s)
if s=="" or s[0]=='0':
return 0
if length==1:
return 1
result=[]
result.append(1)
if int(s[0:2])>26:
if int(s[1])==0:#301,第二个数是0的情况下
return 0
result.append(1)
else:
if int(s[0:2])==10 or int(s[0:2])==20:
result.append(1)
else:
result.append(2)
i=2
while i<length:
two=int(s[i-1:i+1])
if two<27:
if two==0:
return 0
elif two>0 and two<10:
result.append(result[i-1])
elif two==10 or two==20:
result.append(result[i-2])
else:
result.append(result[i-1]+result[i-2])
else:#two>26
if int(s[i])==0:
return 0
result.append(result[i-1])
i+=1
return result[i-1]