Skip to content

Instantly share code, notes, and snippets.

@coopermaruyama
Created December 28, 2023 13:49
Show Gist options
  • Save coopermaruyama/01f588b3b378bc6cbb44d205a5601b77 to your computer and use it in GitHub Desktop.
Save coopermaruyama/01f588b3b378bc6cbb44d205a5601b77 to your computer and use it in GitHub Desktop.
decodeway
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