AI solution for JavaScript Coding Question on BFE.dev
173. uncompress string
Here's a possible solution in JavaScript:
function uncompress(str) { let stack = []; let currentStr = ''; let currentNum = 0; for (let i = 0; i < str.length; i++) { let c = str.charAt(i); if (isDigit(c)) { currentNum = currentNum * 10 + parseInt(c); } else if (c === '(') { stack.push(currentStr); stack.push(currentNum); currentStr = ''; currentNum = 0; } else if (c === ')') { let k = stack.pop(); let prevStr = stack.pop(); currentStr = prevStr + currentStr.repeat(k); } else { currentStr += c; } } return currentStr;}function isDigit(c) { return c >= '0' && c <= '9';}
The idea is to use a stack to keep track of the strings and numbers that we encounter while iterating through the input string. We maintain two variables currentStr
and currentNum
, which represent the substring we're currently building and the number of times we should repeat it, respectively. Whenever we encounter a digit, we add it to currentNum
. Whenever we encounter an opening parenthesis, we push the current state onto the stack and start a new one. Whenever we encounter a closing parenthesis, we pop the previous state from the stack and use it to repeat the current substring currentStr
k
times. Finally, whenever we encounter a non-special character, we simply add it to currentStr
.
Overall, this algorithm runs in linear time O(n), where n is the length of the input string, since we only iterate once through the input and perform constant-time operations with the stack and string manipulation.