https://www.acmicpc.net/problem/4949
4949번: 균형잡힌 세상
각 문자열은 마지막 글자를 제외하고 영문 알파벳, 공백, 소괄호("( )"), 대괄호("[ ]")로 이루어져 있으며, 온점(".")으로 끝나고, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마지막에
www.acmicpc.net
📌 작성한 코드
// 4949
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "Beakjoon/Gold/test.txt";
let input = fs.readFileSync(filePath).toString().trim().split("\n");
while (true) {
const str = input.shift();
if (str === ".") break;
const stack = [];
[...str].forEach((s) => {
if (s === "(" || s === "[") stack.push(s);
if (s === ")") {
if (stack.length && stack[stack.length - 1] === "(") stack.pop();
else stack.push(s);
}
if (s === "]") {
if (stack.length && stack[stack.length - 1] === "[") stack.pop();
else stack.push(s);
}
});
stack.length ? console.log("no") : console.log("yes");
}
📌 풀이
스택에 괄호를 넣어서 짝이 맞춰지면 stack에서 삭제한다.
괄호의 시작인 (, [가 오면 바로 넣어주고, 괄호를 닫는 ),]가 오면 스택의 맨 끝에 있는 괄호와 짝을 맞춰보고 짝이 맞으면 스택에서 꺼내고, 짝이 맞지 않으면 현재 괄호를 다시 스택에 넣는다. 전부 확인한 후에 스택에 남아있는 괄호가 있다면 짝이 맞춰지지 않았다는 의미이므로 no를 출력한다.
✅ 성공

'알고리즘 > 백준' 카테고리의 다른 글
| [JavaScript/Stack] 백준 실버 2 : 10799 - 쇠막대기 (0) | 2024.01.23 |
|---|---|
| [JavaScript/Stack] 백준 실버 4 : 3986 - 좋은 단어 (0) | 2024.01.23 |
| [JavaScript] 백준 골드 5 : 5430 - AC (1) | 2024.01.23 |
| [JavaScript/Queue] 백준 실버 3 : 1021 - 회전하는 큐 (0) | 2024.01.23 |
| [JavaScript/Deque] 백준 실버 4 : 10866 - 덱 (0) | 2024.01.23 |