题目:
题目链接: https://leetcode-cn.com/problems/decode-ways/
解题思路:
动态规划
最后一位如果不是0,只有1中解码方式
从倒数第二位开始,假设索引值为index,共有下述3种情况:
- s[index] = 0,跳过当前位继续遍历
- 0 < s[index] <= 26,当前为有效位,则index位的解码方式累加 index + 1的解码方式
- 0 < s[index:index + 2] <= 26,当前位 + 下一位为有效位,则index位的解码方式累加index + 2的解码方式
代码实现:
class Solution:
def numDecodings(self, s: str) -> int:
# 此处dp数组初始化长度 + 1,原因如下:
# 如果最后一位是0,直接跳过,不需要叠加多余出来的一项
# 如果最后一位不是0,是有效值,相当于对最后一位初始化为了0
# 如果倒数第二位 + 倒数第一位是有效值,则不用添加特殊处理,与其他情况处理方式相同
# dp[index] = dp[index + 1] + dp[index + 2]
# 避免了倒数第二位index + 2时下标溢出
dp = [0] * (len(s) + 1)
dp[-1] = 1
for index in range(len(s) - 1, -1, -1):
double_str = 0
if index < len(s) - 1:
double_str = int(s[index:index + 2])
if '0' == s[index]:
continue
elif 0 < double_str <= 26:
dp[index] += dp[index + 1] + dp[index + 2]
else:
dp[index] += dp[index + 1]
return dp[0]