Skip to content

Instantly share code, notes, and snippets.

@kottenator
Last active March 4, 2018 16:53
Show Gist options
  • Save kottenator/62e18c7faa9c661e9a770b1579c5db0a to your computer and use it in GitHub Desktop.
Save kottenator/62e18c7faa9c661e9a770b1579c5db0a to your computer and use it in GitHub Desktop.
CodeFights: decodeString - O(n) solution
/**
* Solution for this - https://codefights.com/interview-practice/task/dYCH8sdnxGf5aGkez
*/
function decodeString(s) {
return parse(s)[0];
}
function parse(string, startIdx=0) {
let i = startIdx;
let res = '';
let part = '';
let number = '';
while (i < string.length) {
let c = string[i];
i++;
if (/\d/.test(c)) {
number += c;
} else if (c === '[') {
[part, i] = parse(string, i);
res += multiply(part, parseInt(number));
number = '';
} else if (c === ']') {
break;
} else {
res += c;
}
}
return [res, i];
}
function multiply(s, n) {
let out = '';
for (let i = 0; i < n; i++)
out += s;
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment