Leetcode练习(python):字符串类:第91题:解码方法:一条包含字母 A-Z 的消息通过以下方式进行了编码: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 给定一个只包含数字的非空字符串,请计算解码方法的总数。

题目:
解码方法:一条包含字母 A-Z 的消息通过以下方式进行了编码:  'A' -> 1 'B' -> 2 ... 'Z' -> 26 给定一个只包含数字的非空字符串,请计算解码方法的总数。  
思路:
一开始理解错题目了,使用字典去对应,发现题目要求不是这样的。
之后使用动态规划来做,需要考虑的情况比较多,踩了很多坑。
程序:
class Solution:
    def numDecodings(self, s: str) -> int:
        if not s:
            return 0
        if s[0] == '0':
            return 0
        length = len(s)
        counter = 1
        auxiliary_counter = 1
        if int(s) <= 10:
            return 1
        elif 10 < int(s) <= 26:
            if int(s) == 20:
                return 1
            else:
                return 2
        else:
            for index in range(1, length):
                if s[index] == '0':
                    if s[index - 1] == '1' or s[index - 1] == '2':
                        counter = auxiliary_counter
                    else:
                        return 0
                else:
                    if s[index - 1] == '1'  or (s[index - 1] == '2' and '1' <= s[index] <= '6'):
                        auxiliary = counter
                        counter += auxiliary_counter
                        auxiliary_counter = auxiliary
                    else:
                        auxiliary_counter = counter
        return counter
posted on 2020-05-07 17:47  桌子哥  阅读(1312)  评论(0编辑  收藏  举报