[和小菜鸡一起刷题(python)] LeetCode 91. 解码方法 (Decode WAYS)

LeetCode 91. 解码方法 (Decode WAYS)

原题

一条包含字母 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) 。

思路

类似经典的爬楼梯问题,每次可以前进一步或两步,用动态规划来解决。不同的是,此题前进两步存在一定的条件,数值上必须在10到26之间。此外,由于‘0’的出现可能造成无法解码的问题。只有当‘0’之前出现‘1’或‘2’时才能继续解码。因此对于位置i,先判断其是否为‘0’。判断能否解码,不能则返回0。再判断s[i-1:i+1]的数值来决定要到达当前位置i是能只能通过前进两步,一步还是一或两步都可以。

代码

class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s[0] == '0':
            return 0
        last_1 = 1
        last_2 = 1
        for i in range(1,len(s)):
            if s[i] == '0' and (s[i-1] != '1' and s[i-1] != '2'):
                return 0
            if int(s[i-1:i+1]) <= 26 and s[i]!='0':
                tmp = last_2 + last_1
            if s[i] != '0' and (int(s[i-1:i+1]) > 26 or s[i-1]=='0'):
                tmp = last_1
            if s[i] == '0' and (s[i-1] == '1' or s[i-1] == '2'):
                tmp = last_2
            last_2 = last_1
            last_1 = tmp
        return last_1

猜你喜欢

转载自blog.csdn.net/weixin_42771166/article/details/85208580