[LeetCode] Decode Ways(!!!DP)

本文介绍了一种用于解码数字字符串的算法,该算法基于字母到数字的映射规则,能够计算出解码的不同可能性总数。文章详细解释了四种特殊情况,并提供了一个C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Decode Ways My Submissions Question Solution Total Accepted: 47576
Total Submissions: 290697 Difficulty: Medium A message containing
letters from A-Z is being encoded to numbers using the following
mapping:

‘A’ -> 1 ‘B’ -> 2 … ‘Z’ -> 26 Given an encoded message containing
digits, determine the total number of ways to decode it.

For example, Given encoded message “12”, it could be decoded as “AB”
(1 2) or “L” (12).

The number of ways decoding “12” is 2.

题目意思比较容易理解,特殊的有以下几种
(1)00:res[i]=0(无法解析,没有可行解析方式);
(2)10, 20:res[i]=res[i-2](只有第二种情况成立);
(3)11-19, 21-26:res[i]=res[i-1]+res[i-2](两种情况都可行);
(4)01-09, 27-99:res[i]=res[i-1](只有第一种情况可行);

综合上面的,我们可以设计三个变量,a,b,c分别代表i-2,i-1和i处的方式数。
如果num[i-1]>0时我们才c+=b;如果num[i-2]*10+num[i-1]满足大于9且小于27时我们c+=a;

class Solution {
public:
    int numDecodings(string s) {
        int length = s.size();
        if(length==0)   return 0;
        int a=1;
        int b ,c;
        if(s[0]=='0') b = 0;
        else b = 1;
        c=0;
        if(length==1)   return b;
        for(int i = 2; i <=length; ++i){
            int num = stoi(s.substr(i-1,1));
            if(num>0)//01~09,27~99;11~19,21~26
                c = b;
            num = stoi(s.substr(i-2,2));
            if(num>9&&num<27)   //11~19,21~26
                c+=a;
            a=b;
            b=c;
            c=0;
        }
        return b;
    }
};

O(n) 4msAC

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值