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合法的规则只有10和20,判断前面的字符是否为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();
}
};
本文介绍了一种使用动态规划解决数字字符串解码问题的方法。给定一个由数字组成的字符串,每1到26之间的数字可以映射成一个大写字母,目标是计算出该字符串可能解码成的不同字母组合的数量。

2063

被折叠的 条评论
为什么被折叠?



