class Solution {
//DFS here will be TLE
//So the intuitive is that this can be solved by DP
//get the maximum or minimum or number, we should give DP a shot for these kind of problems
//transform equation:
//if(IsCode(i)) f[i]+=f[i-1]
//if(IsCode(i-1, i)) f[i]+=f[i-2]
//initialize: f[0]=1, f[1]=IsCode(s[0])
public:
bool IsCode(string s, int start, int end)
{
if(end-start+1 >= 3) return false;
if(s[start] == '0') return false;
int res = 0;
for (int i = start; i <= end; ++i)
res = res*10+s[i]-'0';
if(res >= 1 && res <= 26)
return true;
}
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = s.size();
if(n == 0) return 0;//note here
vector<int> f(n+1, 0);
f[0] = 1;
if( IsCode(s, 0, 0) ) f[1] = 1;//when use constant subscript, always remember will it out of range?
for (int i = 2; i <= n; ++i)
{
if( IsCode(s, i-1, i-1) ) f[i] += f[i-1];
if( IsCode(s, i-1-1, i-1) ) f[i] += f[i-2];
}
return f[n];
}
};
second time
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;
vector<int> f(s.size()+1, 0);
f[0] = 1;
if(s[0] != '0') f[1] = 1;
for(int i = 2; i <= s.size(); ++i)
{
int curDigit = s[i-1]-'0';
int prevDigit = s[i-2]-'0';
int sum = prevDigit*10+curDigit;
if(sum >= 10 && sum <= 26) f[i] += f[i-2];
if(curDigit != 0) f[i] += f[i-1];
}
return f[s.size()];
}
};