LeetCode 091: Decode Ways

本文介绍了一种中等难度的算法题——解码方式计数。消息中的字母被编码成1到26的数字,文章详细解释了如何计算一个数字串能解码成的不同字母组合的数量,并给出了高效的循环实现而非递归。

091. Decode Ways

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.

思路

类似斐波那契数列,以“12304”的解码为例,用以下表达式表示解码可得到的不同结果数:
f(“12304”) = f(“1230”)g(“4”) + f(“123”)g(“04”);
f(“1230”) = f(“123”)g(“0”) + f(“12”)g(“30”)。
g(s)判断s是否可以解码得到单个字母,返回结果只有1和0,如g(“1”)=1,g(“27”)=0。
此外需要注意“0”和“04”都不可解码,即只要‘0’为字符串的第一个字符,该字符串不可解码,g(“0.*”) = 0。
用循环比递归更高效,减少重复运算。

代码

[C++]

class Solution {
public:
    int numDecodings(string s) {
        if (s.size() <= 0)
            return 0;
        int numOne, numTwo;
        numOne = numTwo = 1;
        int Final = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '0') 
                numTwo = 0;
            Final = numTwo;
            if (IsEncoded(s, i))
                Final += numOne;
            numOne = numTwo;
            numTwo = Final;
        }
        return Final;
    }
    bool IsEncoded(const string &s, int index) {
        if (index < s.size() && index > 0) {
            string temp(s, index - 1, 2);
            int num = stoi(temp, NULL);
            if (num > 9 && num <= 26)
                return true;
        }
        return false;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值