
https://www.acmicpc.net/problem/9012
이게 도대체 뭐야? 했는데 풀고 나니 너무 쉬워서 어이가 없었던 문제 ..
처음에는 그냥 열고 닫는 괄호의 개수가 같은지만 세면 되는거 아닌가? 했는데, 열고 닫는 괄호의 개수만 동일하고 ()의 형태가 되지 않는 경우가 있을 수 있어서 기각.
그럼 자바스크립트 정규식으로 ()를 계속 제거하는 건? 괄호를 없앨 수는 있지만, ()의 형태인지까지는 체크할 수 없어서 기각.
결국 짝을 맞추어봐야하네.. 라고 생각하다보니 스택을 이용하면 짝을 맞출 수 있다는 걸 깨달았다💡
무조건 여는 괄호가 먼저 있어야하고, 닫는 괄호는 나중에 와야한다.
스택에 주어진 문자열을 차례대로 넣다가 ()가 만들어지면 스택에서 빼버리면 된다.
문자열을 모두 스택에 넣었을 때 스택이 비어있으면 VPS이고, 문자가 하나라도 남아있으면 VPS가 될 수 없다.
for (let i = 0; i < n; i++) {
for (let j = 0; j < strings[i].length; j++) {
stack.push(strings[i][j]);
if (stack[stack.length - 2] + stack[stack.length - 1] == "()") {
stack.pop();
stack.pop();
}
}
if (stack.length == 0) answer.push("YES");
else answer.push("NO");
stack = [];
}
이렇게 구현을 하고, 채점이 너무 느린 것 같아서 중첩된 for문의 내용을
if (stack.length > 0 && stack[stack.length - 1] == "(" && strings[i][j] == ")") stack.pop();
else stack.push(strings[i][j]);
이렇게 수정해봤는데, 성능은 비슷한 것 같다..ㅎㅎ
순회하는 반복문이 중첩되어있어서 최적화하는 데에도 한계가 있는 것 같다😢
function solution(n, strings) {
const answer = [];
let stack = [];
for (let i = 0; i < n; i++) {
for (let j = 0; j < strings[i].length; j++) {
stack.push(strings[i][j]);
if (stack[stack.length - 2] + stack[stack.length - 1] == "()") {
stack.pop();
stack.pop();
}
}
if (stack.length == 0) answer.push("YES");
else answer.push("NO");
stack = [];
}
return answer.join("\n");
}
// =====입출력=====
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
rl.on("line", (line) => {
input.push(line);
if (input.length === parseInt(input[0]) + 1) {
rl.close();
}
}).on("close", () => {
const n = parseInt(input[0]);
let strings = input.slice(1, n + 1);
console.log(solution(n, strings));
});

두번째는 실수..ㅎㅎ
너무 어두워보여요...ㅠㅠ