Algorithm/BOJ

[알고리즘/백준/9012] 괄호(스택)

개발자 김비숑 2023. 5. 25. 12:04
반응형

문제


https://www.acmicpc.net/problem/9012

 

9012번: 괄호

괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고

www.acmicpc.net

 

풀이


const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let [n, ...arr] = fs.readFileSync(filePath).toString().trim().split("\n");

const N = +n;
const ps = arr.map((pair) => pair.split(""));

const answer = [];

for (let i = 0; i < N; i++) {
  const stack = [];
  for (let [idx, p] of ps[i].entries()) {
    stack.push(p);

    if (p === ")") {
    // 첫 입력이 ')'이면 NO 출력 
      if (idx === 0) {
        break;
      }
      // 이전 요소가 '('이면 '()' pop하기 
      if (stack.at(-2) === "(") {
        stack.pop();
        stack.pop();
      }
    }
  }
  if (stack.length === 0) answer.push("YES");
  else answer.push("NO");
}

console.log(answer.join("\n"));

 

반응형