Last active
February 9, 2020 07:46
-
-
Save RP-3/20feb963c316775f49bb6e968f44cdaf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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