240716

๋ฌธ์ œ : ๊ด„ํ˜ธ ํšŒ์ „ํ•˜๊ธฐ ๋‚œ์ด๋„ : Lv.2 ์„ค๋ช… :

๋‹ค์Œ ๊ทœ์น™์„ ์ง€ํ‚ค๋Š” ๋ฌธ์ž์—ด์„ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ด๋ผ๊ณ  ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.

(), [], {} ๋Š” ๋ชจ๋‘ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค. ๋งŒ์•ฝ A๊ฐ€ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ด๋ผ๋ฉด, (A), [A], {A} ๋„ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, [] ๊ฐ€ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ด๋ฏ€๋กœ, ([]) ๋„ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค. ๋งŒ์•ฝ A, B๊ฐ€ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ด๋ผ๋ฉด, AB ๋„ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, {} ์™€ ([]) ๊ฐ€ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ด๋ฏ€๋กœ, {}([]) ๋„ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค. ๋Œ€๊ด„ํ˜ธ, ์ค‘๊ด„ํ˜ธ, ๊ทธ๋ฆฌ๊ณ  ์†Œ๊ด„ํ˜ธ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด s๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์ด s๋ฅผ ์™ผ์ชฝ์œผ๋กœ x (0 โ‰ค x < (s์˜ ๊ธธ์ด)) ์นธ๋งŒํผ ํšŒ์ „์‹œ์ผฐ์„ ๋•Œ s๊ฐ€ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด์ด ๋˜๊ฒŒ ํ•˜๋Š” x์˜ ๊ฐœ์ˆ˜๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

ํ’€์ด

function solution(s) {
    let answer = 0;
    let stack = [];
    let isCorrect = true;
    
    for(let i = 0; i < s.length; i++) {
        let arr = s.slice(i) + s.slice(0 , i)
        isCorrect = true
        if(s.length % 2 === 1) return 0
        
        for(str of arr) {
            if(str === '{' || str === '[' || str === '(') {
                stack.push(str)
            } else {
                let top = stack.pop()
                if(top === '(' && str === ')') continue;
                if(top === '{' && str === '}') continue;
                if(top === '[' && str === ']') continue;
                isCorrect = false
                break;
            }
        }
        if (isCorrect) answer++;
    }
    return answer;
}

Last updated