題目:
解碼方法:一條包含字母 A-Z 的消息通過以下方式進行了編碼: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 給定一個只包含數字的非空字符串,請計算解碼方法的總數。
思路:
一開始理解錯題目了,使用字典去對應,發現題目要求不是這樣的。
之后使用動態規划來做,需要考慮的情況比較多,踩了很多坑。
程序:
class Solution:
def numDecodings(self, s: str) -> int:
if not s:
return 0
if s[0] == '0':
return 0
length = len(s)
counter = 1
auxiliary_counter = 1
if int(s) <= 10:
return 1
elif 10 < int(s) <= 26:
if int(s) == 20:
return 1
else:
return 2
else:
for index in range(1, length):
if s[index] == '0':
if s[index - 1] == '1' or s[index - 1] == '2':
counter = auxiliary_counter
else:
return 0
else:
if s[index - 1] == '1' or (s[index - 1] == '2' and '1' <= s[index] <= '6'):
auxiliary = counter
counter += auxiliary_counter
auxiliary_counter = auxiliary
else:
auxiliary_counter = counter
return counter