알고리즘(백준)/자료구조

[알고리즘/자료구조] 10828번 : 스택 - python

되다 2023. 3. 2. 20:19

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

 


  • 문제
  • 소요시간: 30분 36초, 처음 코드 16분

 


  • 설계하기(접근방법) 

1. 파이썬 리스트의 성질을 이용하여 메서드를 작성한다

2. n 을 입력받고 n만큼 order을 입력받는다

3. order에 맞는 메서드를 수행한다

 

 


  • 코드(출력)
import sys

def push(array, x):
    return array.append(x)


def pop(array):
    if not array:
        print(-1)
    else:
        print(array.pop())
    return


def size(array):
    print(len(array))


def empty(array):
    if not array:
        print(1)
    else:
        print(0)


def top(array):
    if not array:
        print(-1)
    else:
        print(array[-1])


n = int(input())

array = []

for i in range(n):
    order = sys.stdin.readline().strip()
    if 'push' in order:
        order, x = order.split()
        push(array, x)
    if order == 'pop':
        pop(array)
    if order == 'size':
        size(array)
    if order == 'empty':
        empty(array)
    if order == 'top':
        top(array)

  • 얻어갈 부분

1. 특정 문자열(x)이 해당 문자열(k) 내에 존재하는지 검사할 때는 파이썬에서 if x in k를 사용할 수 있다

2. 시간초과가 나는 경우 sys.stdin.readline을 사용하자.

2-1 sys.stdin.realine은 개행문자를 포함하니 strip() 함수를 사용해서 개행문자를 제거해주자.

3. 다음에는 스택을 클래스로 선언해서 만들어보자