A message containing letters from
A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26Given 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.
1. Dynamic Programming
class Solution {
public:
int numDecodings(string s) {
int n = s.length();
if (n < 1) return 0;
if (s[0] == '0') return 0;
vector<int> ways(n+1, 0);
ways[0] = 1, ways[1] = 1;
for(int i = 2; i <= n; i++) {
ways[i] = ways[i-1];
if (s[i-1] == '0') {
if (s[i-2] == '0' || s[i-2] > '2')
return 0;
else
ways[i] = ways[i-2];
}
else {
if ((s[i-2] == '1') || (s[i-2] == '2' && s[i-1] < '7')) ways[i] += ways[i-2];
}
}
return ways[n];
}
};
2. Notice we look up from no more than two previous result. We can use something similar to calculating Fibonacci series:
class Solution {
public:
int numDecodings(string s) {
int n = s.length();
if (n < 1) return 0;
int T_2 = 1, T_1 = 1;
for(int i =0 ; i < n; i++) {
int T = T_1;
if (s[i] == '0') {
if (i == 0 ||(s[i-1] == '0' || s[i-1] > '2'))
return 0;
else
T = T_2;
}
else if (i > 0 && (s[i-1] == '1' || (s[i-1] == '2' && s[i] < '7')))
T+= T_2;
T_2 = T_1;
T_1 = T;
}
return T_1;
}
};
No comments:
Post a Comment