Decode Ways

本文深入探讨了如何利用动态规划(DP)算法解决编码问题,具体介绍了将字母与数字之间的映射关系进行解码的过程。通过实例分析,解释了如何计算给定编码消息的所有可能解码方式数量。详细步骤包括初始化动态规划数组、迭代过程以及最终计算解码方式总数。此技术在密码学和信息安全领域有着广泛的应用。

摘要生成于 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.

解题思路:

水DP。

class Solution {
public:
    int numDecodings(string s) {
        int dp[10010];
        int n = s.length();
        if(n == 0) return 0;
        if(s[0] == '0') return 0;
        memset(dp, 0, sizeof(dp));
        dp[0] = 1;
        dp[1] = 1;
        for(int i = 2; i <= n; ++i) {
            int x = s[i-1]-'0';
            int y = (s[i-2]-'0')*10+s[i-1]-'0';
            bool ok = false;
            if(x >= 1 && x <= 26) {
                ok = true;
                dp[i] += dp[i-1];
            }
            // 01, 02, ..., 09 是非法的
            if(y >= 10 && y <= 26) {
                ok = true;
                dp[i] += dp[i-2];
            }
            if(!ok) return 0;
        }
        return dp[n];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值