1. 균형잡힌 세상 (백준 4949번)
링크
스택으로 문제 푸는 법을 잘 모르고 있었다. 분명 관련된 내용을 수업시간에 들었던 것 같은데.. 참 어지럽다.
질문 게시판 돌아보며 겨우겨우 풀었다. 이런 일을 줄여보도록 노력해야겠다.
- 문자열을 순회하며 여는 괄호들을 모두 배열에 push 한다.
- 닫는 괄호가 나올 때마다 "배열의 마지막 원소가 여는 괄호인가?" 와 "배열의 길이가 0 이상인가?"를 확인하여 맞다면 pop하고, 아니면 닫는 괄호를 push한다.
내 답안
const fs = require("fs");
const strings = fs
.readFileSync(process.platform === "linux" ? "/dev/stdin" : "./input.txt")
.toString()
.trim()
.split("\n");
for (let i = 0; i < strings.length - 1; i++) {
let s = [];
for (let j = 0; j < strings[i].length; j++) {
const char = strings[i][j];
if (char === "(") s.push(char);
if (char === "[") s.push(char);
if (char === ")") {
if (s.length !== 0 && s[s.length - 1] === "(") {
s.pop();
} else {
s.push(char);
}
}
if (char === "]") {
if (s.length !== 0 && s[s.length - 1] === "[") {
s.pop();
} else {
s.push(char);
}
}
}
console.log(s.length === 0 ? "yes" : "no");
}