Leetcode 91. Decode Ways

Problem

A message containing letters from A-Z can be encoded into numbers using the following mapping:

‘A’ -> “1”
‘B’ -> “2”

‘Z’ -> “26”
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, “11106” can be mapped into:

“AAJF” with the grouping (1 1 10 6)
“KJF” with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because “06” cannot be mapped into ‘F’ since “6” is different from “06”.

Given a string s containing only digits, return the number of ways to decode it.

The answer is guaranteed to fit in a 32-bit integer.

Algorithm

DP. Similar to Fibonacci sequence f(x) = f(x-1) + f(x-2) if the string is belong to “1” to “26”.

Code

class Solution:
    def numDecodings(self, s: str) -> int:
        if not s:
            return 0
        
        sLen = len(s)
        dp = [0] * (sLen + 1)
        dp[0] = 1
        for i in range(1, sLen+1):
            if s[i-1] >= '1' and s[i-1] <= '9':
                dp[i] += dp[i-1]
            if i >= 2 and (s[i-2] == '1' or (s[i-2] == '2' and s[i-1] <= '6')):
                dp[i] += dp[i-2]
                
        return dp[sLen]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值