알고리즘 분류 구현
자료구조
스택
🔗 문제 출처 https://www.acmicpc.net/problem/10828
python
import sys
n = int(sys.stdin.readline())
stack = []
for _ in range(n):
word = sys.stdin.readline().split()
if word[0] == 'push':
stack.append(word[1])
elif word[0] == 'pop':
print(stack.pop(len(stack)-1)) if len(stack) != 0 else print(-1)
elif word[0] == 'size':
print(len(stack))
elif word[0] == 'empty':
if len(stack) == 0:
print(1)
else:
print(0)
elif word[0] == 'top':
print(stack[len(stack)-1]) if len(stack) != 0 else print(-1)
📌 대표적인 자료구조인 스택에 대한 문제다. 하지만 파이썬은 스택 자료구조를 제공하지 않기 때문에 리스트를 통해 문제를 해결한다.
시간 제한은 0.5초이기 때문에 입력받을 때 input()을 사용한다면 시간 초과가 난다. sys.stdin.readline()을 사용하자.