【LeetCode 中等题】73-解码方法

题目描述:一条包含字母 A-Z 的消息通过以下方式进行了编码:

'A' -> 1
'B' -> 2
...
'Z' -> 26

给定一个只包含数字的非空字符串,请计算解码方法的总数。

示例 1:

输入: "12"
输出: 2
解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。

示例 2:

输入: "226"
输出: 3
解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。

解法1。DP,额……还没理解

class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s or (len(s) > 1 and s[0] == '0'):
            return 0
        dp = [0 for _ in range(len(s)+1)]
        dp[0] = 1
        for i in range(1, len(dp)):
            dp[i] = 0 if s[i - 1] == '0' else dp[i - 1]
            if i > 1 and (s[i - 2] == '1' or (s[i - 2] == '2' and s[i - 1] <= '6')):
                dp[i] += dp[i - 2];
        return dp[-1]

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/86408597