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

 

9012번: 괄호

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

www.acmicpc.net

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split("\n");

const N = Number(input.shift());

for(let i = 0 ; i  < N ; i++) {
    const stack = [];
    let prev = '';
    if(input[i].length % 2 !== 0) console.log("NO");
    else {
        const arr = input[i].split("");
        arr.forEach((a, index) => {
           if(index === 0 && a === ')') {
               return false;
           } else {
               if(stack.length === 0) {
                   stack.push(a);
               } else {
                   prev = stack.pop();
                   if(!(prev === '(' && a === ')')) {
                       stack.push(prev);
                       stack.push(a);
                   }
               }
           }
        });
        if(stack.length === 0) console.log('YES');
        else console.log("NO")
    }
}
728x90

+ Recent posts