10828. 스택
Python Online Compiler & Interpreter
Write and run Python code using our Python online compiler & interpreter. You can build, share, and host applications right from your browser!
replit.com
- 내 풀이
- ⚠️ 시간 초과
- →input() 함수를 사용할 경우, 시간초과 에러가 뜨므로 시간단축을 위해 sys.stdin.readline()을 사용해야함
- 입출력 속도 비교 : sys.stdin.readline > raw_input() > input()
n=int(input())
stack=[]
for _ in range(n):
cmd=input().split()
if cmd[0]=="push":
stack.append(cmd[1])
elif cmd[0]=="pop":
if not stack:
print(-1)
else:
num=stack.pop()
print(num)
elif cmd[0]=="size":
print(len(stack))
elif cmd[0]=="empty":
if stack:
print(0)
else:
print(1)
elif cmd[0]=="top":
if not stack:
print(-1)
else:
print(stack[-1])
- sys 사용
import sys
input=sys.stdin.readline
n=int(input())
...
- 결과
#예제 입력
14
push 1
push 2
top
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
top
#출력 결과
2
2
0
2
1
-1
0
1
-1
0
3
'코딩테스트 > BOJ' 카테고리의 다른 글
| [백준] [실버 3] [DP] 9641) 파도반 수열 (0) | 2022.08.25 |
|---|---|
| [백준] [실버 3] [DP] 1904번. 01타일 (0) | 2022.08.25 |
| [백준] [실버 3] [큐/덱] 1966. 프린터 큐 (0) | 2022.08.25 |
| [백준] [실버1] [그리디] 1931. 회의실 배정 (0) | 2022.07.26 |
| [백준] [실버4] [그리디 알고리즘] 동전 0 (0) | 2022.07.21 |