PS/LeetCode

LeetCode / Stack / 844번 / Backspace String Compare / JS

KimMinJun 2023. 4. 18. 01:28

< 문제 바로가기 >

 

Backspace String Compare - LeetCode

Can you solve this real interview question? Backspace String Compare - Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the tex

leetcode.com

 

< 문제 간단설명 >

문자열 s와 t가 주어진다. 문자열에 #이 있다면 이전에 입력한 문자는 지워진다. 예를들면, "ab#c" 일 경우엔 a를 입력하고 b를 입력하지만 그 다음에 #이 왔으므로 바로 직전에 입력했던 b는 지워진다. 그 후에 마지막으로 c가 입력되어서 최종적으로 "ac"가 된다.

 

위 과정을 s와 t 모두 거친 후, s와 t가 같다면 true, 아니라면 false를 반환한다.

 

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var backspaceCompare = function(s, t) {
    let stackS = [];
    let stackT = [];

    const stacking = (string, stack) => {
        string.split('').forEach((el) => {
            if(el === '#') {
                stack.pop();
            }
            else {
                stack.push(el);
            }
        });

        return stack.join('');
    }

    return stacking(s, stackS) === stacking(t, stackT);
};