512. 解码方法

512. 解码方法

中文English

有一个消息包含A-Z通过以下规则编码

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

现在给你一个加密过后的消息,问有几种解码的方式

样例

样例 1:

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

样例 2:

输入: "10"
输出: 1

注意事项

我们不能解码空串,因此若消息为空,你应该返回0。
消息的长度 n leq 100n100

输入测试数据 (每行一个参数)如何理解测试数据?
 
class Solution:
    """
    @param s: a string,  encoded message
    @return: an integer, the number of ways decoding
    """
    def numDecodings(self, s):
        # write your code here
        if not s or s == '0':return 0 

        dp = [[],[]]  
        dp[0] = [[s[0]]]
        for i in range(1,len(s)):
            dp[i%2] = []
            index = i%2
            for j in range(len(dp[index-1])):
                #单独加
                if (s[i]!= '0'):
                    add_d = dp[index-1][j] + [s[i]]
                    dp[index].append(add_d)
                
                #加尾数
                end_num = dp[index-1][j][-1] + s[i]
                if (int(end_num) <= 26):
                    dp[index-1][j][-1] = end_num
                    dp[index].append(dp[index-1][j])
        return  len(dp[len(s)%2-1])

注:lintcode未通过,你的代码运行时间超过了限制,检查你的时间复杂度.

class Solution:
    """
    @param s: a string,  encoded message
    @return: an integer, the number of ways decoding
    """
    """
    1.最后一步,A-Z之间,只能是f[i-1] + f[i-2]种方法

    10-26 且s[i-1] != 0
    f[i-1] + f[i-2]

    35 这种情况
    0 < s[i-1:i] < 10:
    f[i-1]

    10 or 20
    f[i-2]

    else
    0
    """
    def numDecodings(self, s):
        if not s or s == '0':return 0

        ##123,首个1只是作为12,情况下的1,2和12 这种各一种,12 的方法就是两种
        f = [1,1]

        for i in range(1,len(s)):
            if  10 < int(s[i-1:i+1]) <= 26 and int(s[i]) != 0:
                f.append(f[i-1] + f[i])
            elif 0 < int(s[i:i+1]) < 10:
                f.append(f[i])
            elif int(s[i-1:i+1]) == 10 or int(s[i-1:i+1]) == 20:
                f.append(f[i-1])
            else:
                f.append(0)
        #f多了一个值,f[len(s)]
        return f[len(s)]
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12984789.html