๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section06 - 1 - ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ

by YWTechIT 2021. 8. 31.
728x90

๐Ÿ“ section06 - 1 - ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ

์ด๋ฒˆ ์„น์…˜์€ stack๊ณผ queue ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ๋ฐฐ์šด๋‹ค. ์ด ๋ฌธ์ œ๋ฅผ ํ’€๊ณ  ๋‚˜์„œ ๋ฐฑ์ค€9012 - ๊ด„ํ˜ธ๋ฅผ ํ‘ธ๋Š”๊ฒƒ์„ ์ถ”์ฒœํ•œ๋‹ค.

ํ’€์ด ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. ์ž…๋ ฅ ๊ฐ’์€ ์˜ค์ง (, )๋งŒ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๋ฉด ์กฐ๊ธˆ ๋” ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋‹ค.

 

  1. (๊ฐ€ ๋‚˜์˜ค๋ฉด stack์— pushํ•œ๋‹ค.
  2. )๊ฐ€ ๋‚˜์™”์„ ๋•Œ stack์ด ๋น„์–ด์žˆ๋‹ค๋ฉด ์ง์„ ์ง€์„ ๊ด„ํ˜ธ๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์— false๋ฅผ return ํ•˜๋ฉด ๋˜๊ณ , stack์ด ๋น„์–ด์žˆ์ง€ ์•Š๋‹ค๋ฉด (๋งŒ ์žˆ์„ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— stack.pop()์„ ํ•ด์ค€๋‹ค.
  3. ๋ฐ˜๋ณต๋ฌธ์ด ๋ชจ๋‘ ์ข…๋ฃŒ๋œ ์ดํ›„ stack์„ ๋ดค์„ ๋•Œ ํ•œ ๊ฐœ๋ผ๋„ ๋‚จ์•„์žˆ๋‹ค๋ฉด ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ๊ฐ€ ๋งค์นญ๋˜์ง€ ์•Š์•˜๊ธฐ ๋•Œ๋ฌธ์— false ํ•œ๊ฐœ๋ผ๋„ ์—†์œผ๋ฉด true๋ฅผ ๋ฆฌํ„ดํ•ด์ค€๋‹ค.

 

728x90

 

let s = ")())"

console.log(solution(s));

function solution(s) {
  let stack = [];

  for (let x of s) {
    if (x === "(") stack.push(x);
    else {
      if (stack.length===0) return "NO";
      stack.pop()
    }
  }
  if(stack.length>0) return "NO";
  return "YES";
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€