【leetcode系列】【算法】【中等】解码方法

题目:

题目链接: https://leetcode-cn.com/problems/decode-ways/

解题思路:

动态规划

最后一位如果不是0,只有1中解码方式

从倒数第二位开始,假设索引值为index,共有下述3种情况:

  1. s[index] = 0,跳过当前位继续遍历
  2. 0 < s[index] <= 26,当前为有效位,则index位的解码方式累加 index + 1的解码方式
  3. 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]
发布了100 篇原创文章 · 获赞 4 · 访问量 1471

猜你喜欢

转载自blog.csdn.net/songyuwen0808/article/details/105304856