Leetcode:91. Decode Ways

本文深入探讨了一个将字母映射到数字编码问题的解决方案,涉及了特定输入条件下的复杂性和中断条件的处理。通过分块计算和可能性相乘的方法,我们能够有效地计算出不同编码方式的数量。对于诸如0等特殊输入,文章详细介绍了如何避免错误,并最终确定了解码方式的总数。本篇内容不仅提供了清晰的算法实现,还强调了在处理这类问题时需要关注的细节。

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

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.

这道题感觉难度不是特别大,不过会有一些特殊输入情况题目没有给出来比如 0 等需要跑几遍试出来,造成我的WA特别多
没有出现中断条件时
dp[i][0] = dp[i-1][0]+dp[i-1][j]
dp[i][1] = dp[i][0]
出现中断条件时 s[i] > '2' || s[i-1]<='2'&&s[i] >'6'
分块然后把每块的可能性相乘。

int dp[1000][2]={0};
int numDecodings(char* s) {
    int index;
    if(s[0]=='\0'||s[0]=='0') return 0;
//    dp[1][0]=(s[0]>'0')&&(s[0]<='9')?1:0;
    dp[0][0]=1;
    dp[0][1]=0;
//    dp[1][1]=(s[0]-'2')>0?0:1;
    int carry=0;
    int i =0;
    int sum =1;
    int error=0;
    for (index=1;s[i]!='\0'; index++) {

        if(s[i-1]=='2'&&((s[i]-'6')>0))
        {
            sum*=dp[index-1][0];
            dp[index][0]=1;
            dp[index][1]=0;
            if (s[i+1]=='0') {
                return 0;
            }
        }
        else if ((s[i]-'2')>0)
        {
            sum*=(dp[index-1][0]+dp[index-1][1]);
            dp[index][0]=1;
            dp[index][1]=0;
            if (s[i+1]=='0') {
                return 0;
            }
        }
        else if(s[i]=='0')
        {
            //            sum*=(dp[index-1][0]);
            dp[index][0]=dp[index-2][0];
            dp[index][1]=dp[index-2][1];
            if(s[i+1]=='0')
            {
                return 0;

            }
        }
        else
        {
            error=0;
            carry =dp[index-1][1];
            dp[index][0] = dp[index-1][0]+carry;
            dp[index][1] = (s[i]-'2')>0?0:dp[index-1][0];
            //sum*=dp[index][0];
        }

        if(error>=2)
        {
            return 0;
        }
        i++;
    }

    sum*=dp[index-1][0];
    return sum;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值