leetcode91解码

 

解码,dp,注意特殊情况

 

 

 

 

 

 

 

 

 

def numDecodings( s: str) -> int:
    if len(s) < 1:
        return 1
    if s[0] =='0':
        return 0
    if len(s) == 1:
        return 1
    dp = [0 for i in range(len(s)+1)]
    dp[0] = 1
    dp[1] = 1
    for i in range(2, len(s)+1):
        if s[i-1] =='0':
            if int(s[i-2:i])<=26 and s[i-2]!='0':
                dp[i] = dp[i-2]
            else:
                dp[i]=0
        else:
            if int(s[i-2: i]) <=26 and s[i-2]!='0':
                dp[i] = dp[i-2] + dp[i-1]
            else:
                if s[i-1] == '0':
                    dp[0] = 0
                else:
                    dp[i] = dp[i-1]
    return dp[len(s)]

print(numDecodings('12'))

  

posted @ 2022-06-08 01:18  王毅2016  阅读(26)  评论(0编辑  收藏  举报