Last active
March 4, 2018 16:53
-
-
Save kottenator/62e18c7faa9c661e9a770b1579c5db0a to your computer and use it in GitHub Desktop.
CodeFights: decodeString - O(n) solution
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
/** | |
* 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