코딩테스트/BOJ

[백준][실버 4][스택] 10828. 스택

박소민 2022. 8. 23. 16:20
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