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.
class Solution {
public:
int numDecodings(string s) {
if(s.size() == 0)
return 0;
vector<int> records(s.size());
for(int ii = 0; ii < s.size(); ii ++) {
if(ii >= 1) {
string temp(s, ii - 1, 2);
if("10" <= temp && temp <= "26")
records[ii] += ii - 2 < 0 ? 1 : records[ii - 2];
if('1' <= s[ii] && s[ii] <= '9')
records[ii] += ii - 1 < 0 ? 1 :records[ii - 1];
}
else {
if('1' <= s[ii] && s[ii] <= '9')
records[ii] = 1;
}
}
return records[records.size() - 1];
}
};