[알각코] 인프런 5-3 후위 표기식 만들기 infix => postfix

후위 표기식 만들기

문제 정보는 인프런의 파이썬 알고리즘 문제풀이 코딩테스트에 있습니다!

문제풀이

이 문제는 스택을 이용한 문제풀이이다.

import sys
sys.stdin = open("input.txt", "rt")

a = input()
stack = []
res = ''

for x in a:
  if x.isdecimal():
    res+=x
  else:
    if x=="(":
      stack.append(x)
    elif x=='*' or x=='/':
      while stack and (stack[-1]=="*" or stack[-1]=="/"):
        res+=stack.pop()
      stack.append(x)
    elif x=='+' or x=='-':
      while stack and stack[-1]!="(":
        res+=stack.pop()
      stack.append(x)
    elif x==')':
      while stack and stack[-1]!="(":
        res+=stack.pop()
      stack.pop()

while stack:
  res+=stack.pop()

print(res)