PS/LeetCode

LeetCode / Stack / 394번 / Decode String / JS

KimMinJun 2023. 4. 18. 01:33

< 문제 바로가기 >

 

Decode String - LeetCode

Can you solve this real interview question? Decode String - Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is g

leetcode.com

 

< 문제 간단설명 >

[] 괄호 쌍 안에 있는 문자열을 바로 앞에 온 숫자만큼 반복한다. 예를 들어 "3[a]2[bc]" 일 경우엔, "aaabcbc" 가 된다.

 

/**
 * @param {string} s
 * @return {string}
 */
var decodeString = function(s) {
    let stack = [];
    let curStr = '';
    let curCnt = '';

    s.split('').forEach((el) => {
        if(el === '[') {
            stack.push(curCnt);
            stack.push(curStr);
            curStr = '';
            curCnt = '';
        }
        else if(el === ']') {
            let prevStr = stack.pop();
            let prevCnt = stack.pop();
            curStr = prevStr + curStr.repeat(Number(prevCnt));
        }
        else if('0' <= el && el <= '9') {
            curCnt += el;
        }
        else {
            curStr += el;
        }
    });

    return curStr;
};