leetcode@ [91] Decode Ways (Dynamic Programming)
https://leetcode.com/problems/decode-ways/
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:
bool check(char a, char b) {
int na = a - '0', nb = b - '0';
if(na == 0) return false;
if(na*10 + nb >= 1 && na*10 + nb <= 26) return true;
return false;
}
int numDecodings(string s) {
if(s.length() == 0) return 0;
vector<int> dp(s.length(), 0);
dp[0] = (s[0]=='0')? 0: 1;
if(s.length() == 1) return dp[0];
if(dp[0] == 0) return 0;
else {
bool flag = check(s[0], s[1]);
if(s[1] == '0' && flag) dp[1] = 1;
else if(s[1] == '0' && !flag) return 0;
else if(s[1] != '0' && flag) dp[1] = 2;
else if(s[1] != '0' && !flag) dp[1] = 1;
}
for(int i=2;i<s.length();++i) {
if(s[i] == '0') {
if(check(s[i-1], s[i])) dp[i] = dp[i-2];
else return 0;
}
else {
if(check(s[i-1], s[i])) dp[i] = dp[i-1] + dp[i-2];
else dp[i] = dp[i-1];
}
}
return dp[s.length()-1];
}
};