[백준] 스택 10828번

Kyunglim_Khang·2021년 5월 10일
0

코딩테스트

목록 보기
1/1

https://www.acmicpc.net/problem/10828

import sys

input = sys.stdin.readline

n = int(input())

stack = []

for i in range(n):
    cmd = input().split()
    
    if cmd[0] == "push":
        stack.append(int(cmd[1]))
    
    elif cmd[0] == "pop":
        if len(stack) == 0:
            print(-1)
        else: 
            print(stack.pop())

    elif cmd[0] == "size":
        print(len(stack))
    
    elif cmd[0] == "empty":
        if len(stack) == 0:
            print(1)
        else:
            print(0)

    elif cmd[0] == "top":
        if len(stack) == 0:
            print(-1)
        else:
            print(stack[-1])
  • 처음엔 시간 초과가 떴었는데,
    input()을 sys.stdin.readline() 이걸로 바꿔줬더니 시간 단축되면서 해결.

  • 입력 하나만 받을 때는 input()도 상관없는데, 반복문으로 여러줄 받을 때는 반드시 sys.stdin.readline() 을 사용해야 시간 초과가 발생하지 않는다.

  • 단, 숫자가 아닌 문자열로 입력을 받는 경우엔 줄바꿈(\n)까지 입력으로 받으니
    input().strip() 을 사용하거나 input().strip().split() 을 사용하는 게 좋음.

0개의 댓글