LeetCode(90) Decode Ways

本文介绍如何使用动态规划解决字母数字编码的解码问题,详细解释了解码过程和核心动态转换方程,包括从字符串首部到任意位置的解码方式计算方法。

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


分析如下:

首先题目典型的动态规划风格。用count[i]代表从string s的第0位到第i位的decode的方式, 用s(i, i+2)代表s的从i开始长度为2的sub string.

假设 count[i+2] = 0,而count [i+1], count[i], count[i-1]...count[0]的值都已经算出来了,那么动态转换的方程式将是,
if s(i, i+2) is a valid 2-digit number, then count[i + 2] += count[ i ];

if s(i, i+1) is a valid 2-digit number, then count[i + 2] += count[i + 1];

其中的base case是,计算count[0]和count[1]。

count[0]最多可以有1种decode方式。当s(0, 1)为[1, 9]中(不能包含0)的一个数时,才为1,否则为0,用代码中的辅助函数get_1_number()来计算。

count[1]最多可以有2种decode方式。第一种,仅当s(0,1)和s(1,2)都是一个[1, 9]的数时,第二种,当s(0,2)是一个[10, 26]的数时。


我的代码:

// 12ms 
class Solution {
public:
    int get_1_number(string & s, int index) {
        int result = s[index] - '0';
        return (result <= 9 && result >= 1) ? result : -1;
    }
    
    int get_2_number(string & s,int index) {
        int result = (s[index] - '0') * 10  + s[index + 1] - '0';
        return (result <= 26 && result >= 10) ? result : -1;
    }
    int numDecodings(string s) {
        if (s.length() == 0 ) return 0;
        int * count = new int[s.length()];
        memset(count, 0, sizeof(int) * s.length());

        if (s.length() >= 1 && get_1_number(s, 0) != -1)
            count[0] = 1;
        if (count[0] == 1 && s.length() >= 2 && get_1_number(s, 1) != -1)
            count[1] = count[0];
        if (s.length() >= 2 && get_2_number(s, 0) != -1)
            count[1] ++;
        
        for (int i = 2; i < s.length(); ++i) {
            if (count[i-1] != 0 && get_1_number(s, i) != -1)
                count[i] = count[i-1];
            else
                count[i] = 0;
            if (count[i-2] != 0 && get_2_number(s, i - 1) != -1)
                count[i] += count[i-2];
        }
        int result = count[s.length() - 1];
        delete [] count;
        return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值