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) {
int len = s.length();
if (len == 0)
return 0;
vector<int> ivec(len + 2, 1);
//一维动态规划,从高位到低位比较好做
for (int i = len - 1; i >= 0; --i) {
if (s[i] == '0')
ivec[i] = 0;
else
ivec[i] = ivec[i + 1];
if (i + 1 < len && (s[i] == '1' || (s[i] == '2' && s[i + 1] <= '6')))
ivec[i] += ivec[i + 2];
}
return ivec[0];
}
};