문제
https://www.acmicpc.net/problem/9012
정답 코드1
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
const input = fs.readFileSync(filePath).toString().split("\n");
class Stack {
#array;
constructor(array = []) {
this.#array = array;
}
push(value) {
return this.#array.push(value);
}
pop() {
if (this.#array.length === 0) {
return -1;
}
return this.#array.pop();
}
size() {
return this.#array.length;
}
empty() {
return this.#array.length === 0 ? 1 : 0;
}
top() {
if (this.#array.length === 0) {
return -1;
} else {
return this.#array[this.#array.length - 1];
}
}
}
function solution(input) {
let result = [];
for (let i = 1; i <= input[0]; i++) {
const stack = new Stack();
let isYes = true;
for (let j = 0; j < input[i].length; j++) {
if (input[i][j] === "(") {
stack.push(input[i][j]);
} else {
if (stack.pop() === -1) {
isYes = false;
break;
}
}
}
if (stack.size() !== 0) {
isYes = false;
}
isYes ? result.push("YES") : result.push("NO");
}
return result;
}
console.log(solution(input).join("\n"));
백준 스택 문제 풀었을 때 직접 만든 Stack 클래스를 활용했다. 물론 그냥 배열 사용하면 코드가 짧아진다. 😅
정답 코드2
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
const input = fs.readFileSync(filePath).toString().split("\n");
function solution(input) {
const results = [];
for (let i = 1; i <= input[0]; i++) {
let count = 0;
let isYes = true;
for (let j = 0; j < input[i].length; j++) {
if (input[i][j] === "(") {
count = count + 1;
} else {
count = count - 1;
if (count < 0) {
isYes = false;
break;
}
}
}
if (isYes && count === 0) {
results.push("YES");
} else {
results.push("NO");
}
}
return results;
}
console.log(solution(input).join("\n"));
스택말고 단순 갯수 세서 구하는 방법도 있다.
'코딩문제풀기' 카테고리의 다른 글
[백준] 1406 | 에디터 | 자바스크립트 (0) | 2024.12.10 |
---|---|
[백준/9093] 단어 뒤집기 (0) | 2024.12.02 |
[프로그래머스/12916] 문자열 내 p와 y의 개수 (2) | 2024.07.22 |
[프로그래머스/12928] 약수의 합 (0) | 2024.07.21 |
[프로그래머스/12931] 자릿수 더하기 (0) | 2024.07.18 |