[python] 백준: 10828

·2024년 11월 10일

just공부

목록 보기
8/41

스택

문제와 조건은 아래와 같다.

import sys

inputCnt = int(sys.stdin.readline())
stack = []

for _ in range(inputCnt):
    cmd = sys.stdin.readline()
    
    if 'push' in cmd:
        _, x = cmd.split()
        stack.append(int(x))
    elif 'pop' in cmd:
        if stack:
            print(stack.pop())
        else:
            print("-1")
    elif 'size' in cmd:
        print(len(stack))
    elif 'empty' in cmd:
        if stack:
            print('0')
        else:
            print('1')
    else:
        if stack:
            print(stack[-1])
        else:
            print("-1")

처음 풀었던 코드는 input()을 이용하여 풀었었는데, 시간 초과가 떴다..
그래서 다른 분들의 문제 풀이를 몇 개 보았더니 sys.stdin.readline() 을 이용하여 시간을 단축시키면 된다는 사실을 알게 되었다.

이런 부분들은 문제를 많이 접하고 풀어보면서 깨닫는 수 밖에 없겠지 ㅎㅎ

반복문으로 한 줄씩 받았고, 조건문으로 입력받은 명령을 구분했다.
push 같은 경우는 명령과 stack에 넣을 숫자로 구분할 때, split() 을 사용하여 분리해준 후, 숫자만 스택에 넣었다.
pop, empty, top 의 경우에는 조건문을 하나 더 써서 stack이 비어있는 경우와 그렇지 않은 경우로 분리했다.

문제 조건에 문제에 주어진 명령을 제외한 명령은 나오지 않는다기에 else에서 top을 실행시켰다.

profile
Whatever I want | Interested in DFIR, Security, Infra, Cloud

0개의 댓글