알고리즘

(Baekjoon) 백준 10828 - Python - 스택

e_yejun 2021. 4. 10. 13:12
N = int(input())
stack = []
for _ in range(N):
    c = input().split(' ')
    if c[0] == 'push':
        stack.append(int(c[1]))
    elif c[0] == 'pop':
        if len(stack) == 0:
            print(-1)
        else:
            print(stack.pop())
    elif c[0] == 'size':
        print(len(stack))
    elif c[0] == 'empty':
        if len(stack) == 0:
            print(1)
        else:
            print(0)
    elif c[0] == 'top':
        if len(stack) == 0:
            print(-1)
        else:
            print(stack[-1])

* 이 코드로 제출하면 시간 초과가 나게 되는데, input() 함수 대신에 sys.stdin.readline를 사용하면 해결된다.

 

sys.stdin.readline() 로 입력을 받게되면 개행 문자로 받기 때문에 이를 제거해줘야 한다.

숫자일 경우에는 int()로 형변환을 해주면 되고, 문자일 경우에는 strip() 함수를 이용해서 개행을 지워준다.

import sys
input=sys.stdin.readline

N = int(input())
stack = []
for _ in range(N):
    c = input().strip().split()
    if c[0] == 'push':
        stack.append(int(c[1]))
    elif c[0] == 'pop':
        if len(stack) == 0:
            print(-1)
        else:
            print(stack.pop())
    elif c[0] == 'size':
        print(len(stack))
    elif c[0] == 'empty':
        if len(stack) == 0:
            print(1)
        else:
            print(0)
    elif c[0] == 'top':
        if len(stack) == 0:
            print(-1)
        else:
            print(stack[-1])