스택 [ Python ] [ 백준 : 10828 ]
2023. 5. 24. 22:06ㆍ알고리즘/백준
풀이 및 회고
어렵지 않다고 생각했는데 입력부분에서 시간을 잡아먹었던 문제이다. 두가지를 입력받는 push 와 한가지를 입력받는 pop 등등 처리가 필요했다. 이부분은 sys 모듈을 이용해서 해결할 수 있는 문제였다. 그리고 동료분께 배운 bool() 메서드를 이용 하였고 문제를 풀어나가는 것이 순탄했다. 큐 2 문제를 먼저 풀어서그런지 어렵지 않았다.
# 스택
# 1. n 을 입력 받는다.
# 2. n 만큼 반복해 명령을 입력받는다.
# 3. 명령어를 구분해 입력받는다. (push 1 , pop ...)
# 4. 각 조건에 맞는 명령을 실행한다.
'''
elif command[0] == 'top':
if len(stack):
print(stack[-1])
'''
import sys
n = int(input())
list = []
data = []
for i in range(n):
list = sys.stdin.readline().split()
if list[0] == "push":
data.append(list[1])
elif list[0] == "pop":
if bool(data):
print(data.pop())
else:
print(-1)
elif list[0] == "size":
print(len(data))
elif list[0] == "empty":
if bool(data):
print(0)
else:
print(1)
elif list[0] == "top":
if bool(data):
print(data[len(data) -1])
else:
print(-1)
import sys
n = int(sys.stdin.readline())
stack = []
for i in range(n):
command = sys.stdin.readline().split()
if command[0] == 'push':
stack.append(command[1])
elif command[0] == 'pop':
if len(stack):
print(stack.pop())
else:
print(-1)
elif command[0] == 'top':
if len(stack):
print(stack[-1])
else:
print(-1)
elif command[0] == 'size':
print(len(stack))
elif command[0] == 'empty':
if len(stack):
print(0)
else:
print(1)
'알고리즘 > 백준' 카테고리의 다른 글
회전하는 큐 [ Python ] [ 백준 : 1021 ] (1) | 2023.05.24 |
---|---|
제로 [ Python ] [ 백준 : 10773 ] (0) | 2023.05.24 |
소수 구하기 [ Python ] [ 백준 : 1929 ] (0) | 2023.05.23 |
ACM 호텔 [ Python ] [ 백준 : 10250 ] (0) | 2023.05.23 |
알파벳 찾기 [ Python ] [ 백준 : 10809 ] (0) | 2023.05.23 |