[题目]
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.
题意
假设字符串可以映射成数字,’A’ -> 1,’B’ -> 2 … ‘Z’ -> 26,那么现在给出一个字符串数字,问能解码成多少种结果?
分析
一开始看到这个题目,觉得很简单,不明白为什么通过率只有19.2%。以为是简单碰到10+或者20+(<26),解法就加2。
等后面提交了代码,才发现原来输入的数字支付串可能是随机的,也就是说,有一些是不能解码成功的,比如:0,100,130等。然后还有比如1212这样的输入,也不能简单地加2。
本题使用了动态规划DP。
// dp[i] 表示前 i 个字符的解码办法数目
- 遇到字符 ‘0’。前一个字符为 ‘1’ 或者 ‘2’ ,dp[i] = dp[i-2],否则无解,return 0;
- 如果当前字符不为 ‘0’ ,字符前一个为 ‘1’ ,或者本字符小于等于6且前一个字符为 ‘2’ ,dp[i] = dp[i-1] + dp[i+1],如下表;
- 字符前一个字符不符合条件2,dp[i] = dp[i-1];
用例 | dp[i-1] | dp[i-2] | 总共 |
---|---|---|---|
12 | 1-2 | 12 | 2 |
121 | 1-21 即:1- 2-1 、1-21 | 12-1 即:12- 1 | 3 |
1212 | 1-212 即:1- 2-1-2 、1-21-1 、1-2-12 | 12-12 即:12- 1-2 、12-12 | 5 |
12121 | 1-2121 即:1- 2-1-2-1 、1-12-1-1 、1-2-12-1 、1-2-1-21 、1-12-12 | 12-121 即:12- 1-2-1 、12-12-1 、12-1-12 | 8 |
… | … | … | … |
代码
考虑到我们只需要dp[n],为了简化空间复杂度,我使用 pre 、prepre,代替 dp[i-1]、dp[i-2]
int numDecodings(string s) {
if(s.size()==0 || s[0]=='0') return 0;
int pre = 1, prepre = 1, curr = 1;
for(int i=1;i<s.size();i++){
if(s[i] == '0'){
if(s[i-1] == '1' || s[i-1] == '2')
curr = prepre;
else
return 0;
}
else{
if(s[i-1] == '1' || (s[i-1] == '2' && s[i]<='6'))
curr = pre +prepre;
else
curr = pre;
}
prepre = pre;
pre = curr;
}
return curr;
}
耗时:3ms