알고리즘/백준

[백준] 10828번: 스택 (JavaScript, NodeJS)

정현수 2022. 1. 9. 15:44
반응형

 

문제

정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 다섯 가지이다.

  • push X: 정수 X를 스택에 넣는 연산이다.
  • pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 스택에 들어있는 정수의 개수를 출력한다.
  • empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
  • top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.

입력

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.

출력

출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.

예제 입력 1 복사

14
push 1
push 2
top
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
top

예제 출력 1 복사

2
2
0
2
1
-1
0
1
-1
0
3

예제 입력 2 복사

7
pop
top
push 123
top
pop
top
pop

예제 출력 2 복사

-1
-1
123
123
-1
-1

처음 풀이

const fs = require("fs");

// 백준 제출 할 때 주석 제거
const readFileSyncAddress = '/dev/stdin';

// VSC 테스트 할 때 주석 제거
// const readFileSyncAddress = "input.txt";

const input = fs.readFileSync(readFileSyncAddress).toString().trim().split("\n");

const [n, ...commands] = input;

// 문제 풀이
function solution(n, commands) {
	const stack = [];
	for (let i = 0; i < n; i += 1) {
		const command = commands[i].split(' ')[0];
		switch (command) {
			case 'push':
				const pushItem = commands[i].split(' ')[1];
				stack.push(pushItem);
				break;
			case 'pop':
				if (stack.length === 0) console.log(-1);
				else console.log(stack.pop());
				break;
			case 'top':
				if (stack.length === 0) console.log(-1);
				else console.log(stack[stack.length - 1]);
				break;
			case 'empty':
				if (stack.length === 0) console.log(1);
				else console.log(0);
				break;
			case 'size':
				console.log(stack.length);
				break;
			default:
				break;
		}
	}
}

// 제출
solution(n, commands);

처음에는 자바스크립트 내장 메소드들을 이용해서 스택을 풀려고했다.

당연히 시간 초과가 났다.

그래서 top 변수를 이용한 스택을 구현했다.

 

 

정답 풀이

const fs = require("fs");

// 백준 제출 할 때 주석 제거
// const readFileSyncAddress = '/dev/stdin';

// VSC 테스트 할 때 주석 제거
const readFileSyncAddress = "input.txt";

const input = fs.readFileSync(readFileSyncAddress).toString().trim().split("\n");

const [n, ...commands] = input;

// 문제 풀이
function solution(n, commands) {
	const stack = [];
	let top = 0;
	let answer = '';

	for (let i = 0; i < n; i += 1) {
		const command = commands[i].split(' ')[0];
		let result = '';

		switch (command) {
			case 'push':
				const pushItem = commands[i].split(' ')[1];
				stack[top++] = pushItem;
				break;
			case 'pop':
				if (top) {
					top -= 1;
					result = stack.splice(-1);
					answer += result + ' ';
				} else {
					result = -1;
					answer += result + ' ';
				}
				break;
			case 'top':
				result = top ? stack[top - 1] : -1;
				answer += result + ' ';
				break;
			case 'empty':
				result = top ? 0 : 1;
				answer += result + ' ';
				break;
			case 'size':
				result = top;
				answer += result + ' ';
				break;
			default:
				break;
		}
	}

	console.log(answer.split(' ').join('\n'));
}

// 제출
solution(n, commands);

 

반응형