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

·2023년 5월 10일

백준 문제풀이

목록 보기
64/159

백준 1918번


최종 제출 코드

infix = input()
stack = []
postfix = []
sign_dict = {'*':0, '/':0, '+':1, '-':1}

for i in infix:
  
  if i >= 'A' and i <= 'Z':
    postfix.append(i)
    
  else:
    if i=='(':
      stack.append(i)
    elif i in '*/+-':
      while stack and stack[-1] != '(' and sign_dict[i] >= sign_dict[stack[-1]] :
        b = postfix.pop()
        a = postfix.pop()
        sign = stack.pop()
        postfix.append(a+b+sign)
      stack.append(i)
    else: # i == ')'
      while stack[-1] != '(':
        b = postfix.pop()
        a = postfix.pop()
        sign = stack.pop()
        postfix.append(a+b+sign)
      stack.pop()

while len(stack) != 0:
  b = postfix.pop()
  a = postfix.pop()
  sign = stack.pop()
  postfix.append(a+b+sign)

print(postfix[0])

◼ 딕셔너리를 활용해서 연산자의 우선순위 탐색

  • 연산자는 자신보다 낮은 연산자만을 스택에 남겨두고 나머지는 pop한 후 자신이 들어간다.
  • (는 무조건 스택에 들어간다.
  • )는 괄호가 끝났다는 뜻이다. (를 만날 때까지 스택에 남은 연산자를 pop한다.
profile
백엔드 개발자가 되고 싶어요(22.8.15~)

0개의 댓글