이번 문제는 아래 링크에서 풀어볼 수 있습니다/
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
문제
정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 다섯 가지이다.
- 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
정답 코드
나의 풀이
파이썬 Ver.
n = int(input()) def mySolution(n): result = [] inputs = [] for i in range(n): inputs.append(input()) for operate in inputs: if 'push' in operate: operate = operate.split() result.append(int(operate[1])) else: if operate == 'top' and len(result) > 0: print(result[-1]) elif operate == 'top' and len(result) < 1: print(-1) if operate == 'pop' and len(result) > 0: print(result.pop(-1)) elif operate == 'pop' and len(result) < 1: print(-1) if operate == 'size': print(len(result)) if operate == 'empty' and len(result) > 0: print(0) elif operate == 'empty' and len(result) < 1: print(1) mySolution(n)
자바스크립트/NodeJS Ver.const fs = require('fs'); const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt'; let [n, ...input] = fs.readFileSync(filePath).toString().trim().split('\n'); n = parseInt(n); const data = input.map((val) => val.split(' ')); const solution1 = (n, data) => { const stack = []; let result = ''; for (let i = 0; i < data.length; i++) { if (data[i].includes('push')) stack.push(data[i][1]); else { if (data[i][0] === 'top' && stack.length) result += stack[stack.length - 1] + '\n'; else if (data[i][0] === 'top' && !stack.length) result += -1 + '\n'; else if (data[i][0] === 'pop' && stack.length) result += stack.pop() + '\n'; else if (data[i][0] === 'pop' && !stack.length) result += -1 + '\n'; else if (data[i][0] === 'size') result += stack.length + '\n'; else if (data[i][0] === 'empty' && stack.length) result += 0 + '\n'; else if (data[i][0] === 'empty' && !stack.length) result += 1 + '\n'; } } return result.trim(); }; console.log('solution1'); console.log(solution1(n, data));
모범 답안
파이썬 Ver.
import sys n = int(sys.stdin.readline().rstrip()) def exampleAnswer(n): def push(x): stack.append(x) def pop(): return -1 if not stack else stack.pop() def size(): return len(stack) def empty(): return 0 if stack else 1 def top(): return stack[-1] if stack else -1 stack = [] for _ in range(n): input_split = sys.stdin.readline().rstrip().split() oper = input_split[0] if oper == 'push': push(input_split[1]) elif oper == 'pop': print(pop()) elif oper == 'size': print(size()) elif oper == 'empty': print(empty()) elif oper == 'top': print(top()) exampleAnswer(n)
자바스크립트/NodeJS Ver.
const fs = require('fs'); const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt'; let [n, ...input] = fs.readFileSync(filePath).toString().trim().split('\n'); const solution2 = (n, data) => { const push = (num) => stack.push(num); const pop = () => (stack.length ? stack.pop() : -1); const size = () => stack.length; const empty = () => (stack.length ? 0 : 1); const top = () => (stack.length ? stack[stack.length - 1] : -1); const stack = []; let result = ''; for (let i = 0; i < data.length; i++) { switch (data[i][0]) { case 'push': push(data[i][1]); break; case 'pop': result += pop() + '\n'; break; case 'size': result += size() + '\n'; break; case 'empty': result += empty() + '\n'; break; default: result += top() + '\n'; } } return result.trim(); }; console.log('solution2'); console.log(solution2(n, data));
문제 풀이
문제 자체는 어렵지 않은데 input() 메서드를 써서 입력값을 받으면 시간 초과가 뜨기 때문에 애를 먹는 문제이다. 나 같은 경우 입력값을 받는 리스트를 따로 만들어서 입력값에 'push'가 포함되어 있을 때만 split() 메서드를 실행하도록 하니 시간 초과가 뜨지 않았다.
시간 초과를 해결하는 가장 일반적인 방법은 바로 sys 라이브러리를 써서 입력값을 받는 것이다. sys.stdin.readline()으로 입력값을 받으면 prompt message를 인자로 받지 않고 개행 문자를 포함해서 리턴하기 때문에 입력값을 리턴하기 전에 개행 문자를 제거하는 작업을 수행하는 input() 메서드보다 빠르다.
입력값을 잘 정제해서 받았다면 조건문을 작성하여 각 조건에 맞는 동작을 수행하면 된다.
'👩💻 Programming > Coding Test 문제 풀이' 카테고리의 다른 글
[Baekjoon] 9012 괄호(파이썬/자바스크립트/NodeJS) (0) | 2022.12.22 |
---|---|
[Baekjoon] 9093 단어 뒤집기(파이썬/자바스크립트/NodeJS) (0) | 2022.12.21 |
[프로그래머스] level 3 기둥과 보 설치(파이썬/자바스크립트) (0) | 2022.12.18 |
[Baekjoon] 3190 뱀(파이썬/자바스크립트/NodeJS) (0) | 2022.12.15 |
[프로그래머스] level 3 자물쇠와 열쇠(파이썬 python) (0) | 2022.12.14 |
댓글