[백준 / python] 10828번 : 스택

김동준·2023년 10월 8일
0

Data Structure & Algorithm

목록 보기
11/19

알고리즘 분류 구현 자료구조 스택

🔗 문제 출처 https://www.acmicpc.net/problem/10828



📎 코드

python

import sys

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

for _ in range(n):
  word = sys.stdin.readline().split()
  
  if word[0] == 'push':
    stack.append(word[1])
  elif word[0] == 'pop':
    print(stack.pop(len(stack)-1)) if len(stack) != 0 else print(-1)
  elif word[0] == 'size':
    print(len(stack))
  elif word[0] == 'empty':
    if len(stack) == 0:
      print(1)
    else:
      print(0)
  elif word[0] == 'top':
    print(stack[len(stack)-1]) if len(stack) != 0 else print(-1)



📌 대표적인 자료구조인 스택에 대한 문제다. 하지만 파이썬은 스택 자료구조를 제공하지 않기 때문에 리스트를 통해 문제를 해결한다.

시간 제한은 0.5초이기 때문에 입력받을 때 input()을 사용한다면 시간 초과가 난다. sys.stdin.readline()을 사용하자.

profile
동구팔

0개의 댓글

관련 채용 정보