91. Decode Ways
'A' ->1
'B' ->2
...
'Z' ->26class Solution {
public:
int numDecodings(string s) {
unordered_map <string, int> f;
unordered_map <string, int> m;
f.clear();
for(int i = 1; i <= 26; i++){
f[to_string(i)] = 1;
}
m = f; // m is the element dictionary
for(int i = s.length()-2; i>=0; i--){
string sec2end = s.substr(i + 1, s.length() - (i + 1));
string third2end = s.substr(i + 2, s.length() - (i + 2));
if(f.find(sec2end) != f.end() && s[i] != '0' ){
f[s.substr(i, s.length() - i)]+=f[s.substr(i + 1, s.length() - (i + 1))];
}
if(f.find(third2end)!=f.end() && m.find(s.substr(i,2))!=m.end()){
f[s.substr(i, s.length() - i)]+=f[third2end];
}
}
return f[s];
}
};Last updated
Was this helpful?