반응형

문제링크
https://www.acmicpc.net/problem/10828


풀이방법
- 처음에는 switch문으로 따로 만들어서 사용할까 했지만, 객체로 만드는 것이 호출할 때도 stack.pop(), stack.pop() 등의 형태로 호출할 수 있어 직관적이라고 생각하여 객체 형식으로 만들었다.
- 처음에는 for문을 돌면서 push인 경우를 제외하고 바로 console.log로 결과값을 출력했는데 시간초과가 발생했다. 이를 해결하기 위해 console.log를 바로 출력하지 않고 string 형태의 result를 업데이트하고 for문이 종료된 후 한 번만 호출하는 방식으로 변경하여 해결했다.
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const input = [];
rl.on("line", (line) => {
input.push(line);
});
const stack = {
data: [],
push: function (x) {
this.data.push(x);
},
pop: function () {
if (this.data.length === 0) {
return -1;
}
return this.data.pop();
},
size: function () {
return this.data.length;
},
empty: function () {
return this.data.length === 0 ? 1 : 0;
},
top: function () {
if (this.data.length === 0) {
return -1;
}
return this.data[this.data.length - 1];
},
};
rl.on("close", () => {
let result = "";
for (let i = 1; i <= Number(input[0]); i++) {
const [command, value] = input[i].split(" ");
if (command === "push") {
stack.push(value);
continue;
}
result += stack[command]() + "\n";
}
console.log(result);
});
반응형
'개발' 카테고리의 다른 글
[HTTP 완벽 가이드] 17장 내용 협상과 트랜스코딩 (1) | 2025.02.04 |
---|---|
[HTTP 완벽 가이드] 16장 국제화 16.4~16.6 (0) | 2025.02.04 |
[99클럽] 알고리즘 TIL: 백준 32953번 회상 - JavaScript (0) | 2025.01.24 |
[99클럽] 알고리즘 TIL: 백준 31562번 전주 듣고 노래 맞히기 - JavaScript (1) | 2025.01.24 |
[HTTP 완벽 가이드] 16장 국제화 16.1~16.3 (1) | 2025.01.22 |