[알고리즘/백준] 1918: 후위 표기식(python)

유현민·2022년 4월 6일
0

알고리즘

목록 보기
100/253

후위 표기식 2보다 조금 더 어렵다.
괄호가 제일 구현하기 어려웠다. 여는 괄호를 방패라고 생각하고 풀면 쉽다. 괄호보다 먼저 들어간 기호들은 괄호가 있는 한 계속 순위가 밀리게 된다.

a = input()
stack = []
ans = []
for i in a:
    if i.isalpha():
        ans.append(i)
    else:
        if i == '(':
            stack.append(i)
        elif i == '*' or i == '/':
            while stack and (stack[-1] == '*' or stack[-1] == '/'):
                ans.append(stack.pop())
            stack.append(i)
        elif i == '+' or i == '-':
            while stack and stack[-1] != '(':
                ans.append(stack.pop())
            stack.append(i)
        elif i == ')':
            while stack and stack[-1] != '(':
                ans.append(stack.pop())
            stack.pop()
while stack:
    ans.append(stack.pop())
print(*ans, sep='')
profile
smilegate megaport infra

0개의 댓글