본문 바로가기
개발

[99클럽] 알고리즘 TIL: 백준 10828번 스택 - JavaScript

by soyooooon 2025. 2. 3.
반응형

문제링크

https://www.acmicpc.net/problem/10828

백준 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);
});
반응형