Skip to content

Instantly share code, notes, and snippets.

@RP-3
Last active February 9, 2020 07:46
Show Gist options
  • Save RP-3/20feb963c316775f49bb6e968f44cdaf to your computer and use it in GitHub Desktop.
Save RP-3/20feb963c316775f49bb6e968f44cdaf to your computer and use it in GitHub Desktop.
var numDecodings = function(s) {
const memo = new Array(s.length).fill(null); // for performance
const inner = (i) => {
// base cases
if(i === s.length) return 1; // if we make it to the end, we've completed a valid decoding
if(s[i] === '0') return 0; // no decoding can have a leading 0
if(memo[i] !== null) return memo[i]; // for performance
if(i < s.length-1 && parseInt(`${s[i]}${s[i+1]}`, 10) < 27){ // if there are two ways to decode
return memo[i] = inner(i+1) + inner(i+2); // do both
}else{
return memo[i] = inner(i+1); // otherwise just do the one
}
};
return inner(0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment