链接:http://leetcode.com/onlinejudge#question_91
原题:
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.
思路:有点dp的思想,要小心不合法字符串到出现,我第一次就WA了。
考虑元素s[i],只有两种可能:
1)单独解码,当然s[i] != '0'
2) 和s[i-1]结合了解码,要求 s[i-1]s[i]的值在10~26之间,不然不行。
PS:小心0,00的不合法字符串。
代码:
class Solution {
public:
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s.size() == 0)
return 0;
if (s[0] == '0')
return 0;
vector<int> dp(s.size()+1, 0);
dp[0] = dp[1] = 1;
for (int n=2; n<=s.size(); n++) {
int i = n - 1;
if (s[i] != '0')
dp[n] = dp[n-1];
int code = (s[i-1]-'0')*10 + (s[i]-'0');
if (code == 0)
return 0;
else if (code>9 && code<27)
dp[n] += dp[n-2];
}
return dp[s.size()];
}
};