์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜6] ๊ด„ํ˜ธ๋ฌธ์ž์ œ๊ฑฐ (Javascript)

์€์ง„ 2021. 6. 26. 15:33

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜6] ๊ด„ํ˜ธ๋ฌธ์ž์ œ๊ฑฐ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-26

1. x === '('์ธ ๊ฒฝ์šฐ stack.push(x);

2. x === ')'์ธ ๊ฒฝ์šฐ stack.pop();

3. x๊ฐ€ ๋ฌธ์ž์ด๋ฉด์„œ stack.length === 0 ์ธ ๊ฒฝ์šฐ res += x;

for (let x of str) { 
    if (x === '(') stack.push(x);
    else if (x === ')') stack.pop();
    else if (stack.length === 0) res += x;
}


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-26

function solution(str) {
    let res = '';
    let stack = [];

    for (let x of str) {
        if (x === '(') stack.push(x);
        else if (x === ')') stack.pop();
        else if (stack.length === 0) res += x;
    }

    return res;
}