topic:
Topic links: https://leetcode-cn.com/problems/decode-ways/
Problem-solving ideas:
Dynamic Programming
If the last digit is not 0, only 1 decoding mode
Starting from the penultimate position, assuming index value index, a total of the following three cases:
- s [index] = 0, skip the current bit continue traversing
- 0 <s [index] <= 26, the current position is valid, then the bit index decoder decodes index + cumulative manner to Embodiment 1
- 0 <s [index: index + 2] <= 26, the current bit + a valid bit, the bit index additive decoding method of decoding scheme index + 2
Code:
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]