[백준 1918번 ] 후위 표기식 (stack, python)

728x90
반응형

www.acmicpc.net/problem/1918

 

1918번: 후위 표기식

첫째 줄에 중위 표기식이 주어진다. 단 이 수식의 피연산자는 A~Z의 문자로 이루어지며 수식에서 한 번씩만 등장한다. 그리고 -A+B와 같이 -가 가장 앞에 오거나 AB와 같이 *가 생략되는 등의 수식

www.acmicpc.net

 

import sys
from math import sqrt
input=sys.stdin.readline

d={'*':2,'/':2,'+':1,'-':1,'(':0,')':0}
q=[]
s=input().strip()
for x in s:
    # 알파벳 출력
    if x not in d:
        print(x,end='')
    #왼쪽 괄호 
    elif x=='(':
        q.append(x)
    # 오른쪽 괄호시 왼쪽 괄호 나올때까지 중간 연산자 출력한다 
    elif x==')':
        while q:
            cur=q.pop()
            if cur=='(': break
            print(cur,end='')
    else:
        # 우선순위가 더 낮다면 이전에 우선순위 높은 연산자를 출력한다 
        while q and q[-1]!='(' and d[x]<=d[q[-1]]:
            print(q.pop(),end='')
        q.append(x)

# 나머지 연산자를 출력한다 
while q:
    print(q.pop(),end='')







728x90
반응형
TAGS.

Comments