Match the currnet idx as one or two-digit and recursively do this, also maintain a memo to avoid re-calculation.
Also, originally I’m using stoi(s.substr(s, 2)), where the chatGPT recommends to use (s[idx]-'0)*10 + s[idx+1] -'0', and I find that this approach is much faster.
Code
class Solution {
public:
int numDecodings(string s) {
memo.assign(s.size(), -1);
return decoding(s, 0);
}
int decoding(const string& s, int idx) {
int n = s.size();
if(idx > n-1) return 0;
int totalCnt = 0;
if(memo[idx] != -1) return memo[idx];
if(s[idx] != '0') {
totalCnt += idx == n-1 ? 1 : decoding(s, idx+1);
}
if( idx <= n-2 &&
(s[idx]-'0')*10 +(s[idx+1]-'0') <= 26 &&
s[idx] != '0') {
totalCnt += idx == n-2 ? 1 : decoding(s, idx+2);
}
memo[idx] = totalCnt;
return totalCnt;
}
vector<int> memo;
};