[leetcode 91] Decode Ways

本文介绍了一种使用动态规划解决数字字符串解码问题的方法。给定一个由数字组成的字符串,每1到26之间的数字可以映射成一个大写字母,目标是计算出该字符串可能解码成的不同字母组合的数量。

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.

题意:
给你一串数字,你能解码出多少种不同的英文串,编码规则如题
解法: 动态规划
假定s[0...i]的解码方法有n种,那么下一步怎么求解s[0…i+1]有多少种?
1. s[i+1] = 0 : 因为0不能自身成为一个字母,也不存在类似01这样的编码规则,所以0合法的规则只有1020,判断前面的字符是否为1或者2,如果不是则该数字串出现无效编码,返回0;否则s[0…i+1]的编码数等于s[0…i-1]的情况(i, i + 1必须在一起)
2. s[i+1] = 1-5 : 考虑s[i] = ‘1-2’,如果等于,则有两种匹配情况,s[0…i+1] = s[0…i] + s[0…i-1];否则s[i+1]只能单独编码,s[0…i+1] = s[0…i]
3. s[i+1] = 6-9 : 考虑s[i] = ‘1’,如果等于,则有两种匹配情况,s[0…i+1] = s[0…i] + s[0…i-1];否则s[i+1]只能单独编码,s[0…i+1] = s[0…i]

C++代码实现:

static string x = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return "";
}();

class Solution {
public:
    int numDecodings(string s) {
        if(s.empty() || s[0] == '0') return 0;
        vector<int> a(s.size() + 1);
        a[0] = a[1] = 1;
        for(int i = 1; i < s.size(); ++i){
            if(s[i] == '0'){
                if(s[i-1] == '0' || s[i-1] > '2') return 0;
                a[i+1] = a[i-1];
            }
            else if(s[i-1] == '0' || s[i-1] > '2' || (s[i-1] == '2' && s[i] > '6')) a[i+1] = a[i];
            else a[i+1] = a[i] + a[i-1];
        }
        return a.back();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值