Created
December 28, 2023 13:49
-
-
Save coopermaruyama/01f588b3b378bc6cbb44d205a5601b77 to your computer and use it in GitHub Desktop.
decodeway
This file contains 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
const map = 'abcdefghijklmnopqrstuvwxyz' | |
.split('') | |
.reduce((obj, curr, i) => ({ | |
...obj, | |
[String(i+1)]: curr.toUpperCase() | |
}), {}) | |
/** | |
* @param {string} s | |
* @return {number} | |
*/ | |
var numDecodings = function(s) { | |
let decodings = [{head:'',tail:s}]; | |
let count = 0 | |
const seen = {} | |
while (decodings.length) { | |
const next = []; | |
for (const d of decodings) { | |
// already done | |
if (seen[d.head]) continue | |
if (!d.tail.length) { | |
count++ | |
seen[d.head] = true | |
continue; | |
} | |
const r = decode(d); | |
next.push(...r.results); | |
} | |
decodings = next | |
} | |
return count | |
}; | |
function decode(obj) { | |
const results = []; | |
const a = obj.tail[0]; | |
const b = obj.tail[1]; | |
const comb = [a]; | |
if (a === '0') { | |
return { valid: false, results } | |
} | |
if (b) { | |
comb.push(a+b) | |
} | |
for (const c of comb) { | |
if (map.hasOwnProperty(c)) { | |
results.push({ | |
head: obj.head + map[c], | |
tail: obj.tail.slice(c.length) | |
}) | |
} | |
} | |
return { valid: true, results } | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment