【算法题12 解码方法decode way】

1、来源LeetCode91

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

解题代码:

class Solution:
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        l_s=len(s)
        if l_s==0 or s[0]=='0':
            return 0
        one=1
        two=ans=0
        for i in range(1,l_s+1):
            temp_one=int(s[i-1])
            temp_two=int(s[i-2:i]) if i>=2 else None
            ans=one*int(temp_one!=0)+two*int(temp_two!=None and temp_two>=10 and temp_two<=26)
            one,two=ans,one
        return ans
        

 

posted @ 2018-08-23 15:23  Fintech带你飞  阅读(488)  评论(0编辑  收藏  举报