coding test - python/백준
백준 / 10828번 스택 / Python 파이썬
sillon
2022. 5. 4. 18:19
728x90
반응형
*문제 출처는 백준에 있습니다.
문제 제목: 스택
문제 사이트: https://www.acmicpc.net/problem/10828
나의 풀이
import sys
n = int(sys.stdin.readline())
new_stack = []
cnt = 0
for _ in range(n):
tmp = sys.stdin.readline().split()
if tmp[0] == "push":
new_stack.append(tmp[1])
elif tmp[0] == "pop":
if new_stack == []:
print(-1)
else:
print(new_stack[-1])
new_stack.pop()
elif tmp[0] == "size":
print(len(new_stack))
elif tmp[0] == "empty":
if new_stack == []:
print(1)
else:
print(0)
elif tmp[0] == "top" :
if new_stack !=[]:
print(new_stack[-1])
else:
print(-1)
import sys
sys.stdin.readline() 을 이용하여 입력 받는 시간을 단축하여, 시간초과를 없애주어야 정답으로 인정됨
※ 알아야 할 것
- stack은 LIFO(Last-in-First-Out) 자료구조로 마지막으로 들어간 것을 먼저 꺼낸다. (pop)
- 그냥 input을 넣으면 시간초과가 뜬다. 따라서 import sys의 sys.stdin.readline() 이용!
728x90
반응형