입력받은 식을 하나씩 꺼내면서 각 기호마다 해야할 역할을 조건문 내부에 적어주었다.
곱셈 나눗셈이 나왔을 때, 덧셈 뺄셈이 나왔을 때, '(' 가 나왔을 때, ')' 가 나왔을 때
각 4 가지 경우에 대해 만들어줘야한다.
그리고 식 탐색이 끝났을 때 스택에 남아있는 기호들을 pop으로 빼준다.
도움된 반례
input : A*B-C*D/E
output : AB*CD*E/-
from collections import deque
inn = input()
stack = deque()
result = ''
math = ['(',')','*', '/','+','-']
for i in range(len(inn)):
t = inn[i]
if t==math[0]:
stack.append('(')
elif t==math[1]:
while stack:
out = stack.pop()
if out == '(':
break
result += out
elif t==math[2] or t==math[3]:
if stack and (stack[-1]=='*' or stack[-1]=='/'):
out = stack.pop()
result += out
stack.append(t)
elif t==math[4] or t==math[5]:
while stack:
out = stack.pop()
if out=='(':
stack.append('(')
break
result += out
stack.append(t)
else:
result += t
while stack:
result += stack.pop()
print(result)
'백준' 카테고리의 다른 글
키로거 - 5397번 (0) | 2022.11.07 |
---|---|
절댓값 힙 - 11286번 (0) | 2022.10.31 |
최대 힙 - 11279번 (0) | 2022.10.31 |
최소 힙 - 1927번 (0) | 2022.10.31 |
덩치 - 7568번 (0) | 2022.10.31 |
댓글