====== 후위 표기식 ====== * 스택을 처음 배울 때 연습문제로 자주 등장하는 문제 ===== 풀이 ===== * 유명한 문제라서 해설이 여기저기 많다. [[https://runestone.academy/runestone/books/published/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html|여기]]는 그냥 검색해서 나온 곳이지만 해설로는 충분. ===== 코드 ===== """Solution code for "BOJ 1918. 후위 표기식". - Problem link: https://www.acmicpc.net/problem/1918 - Solution link: http://www.teferi.net/ps/problems/boj/1918 """ PRIORTY_BY_OPERATOR = {'(': -1, '+': 1, '-': 1, '*': 2, '/': 2} def main(): infix = input() stack = [] postfix = [] for ch in infix: if ord('A') <= ord(ch) <= ord('Z'): postfix.append(ch) elif ch == ')': while stack[-1] != '(': postfix.append(stack.pop()) stack.pop() elif ch == '(': stack.append(ch) else: priority = PRIORTY_BY_OPERATOR[ch] while stack and PRIORTY_BY_OPERATOR[stack[-1]] >= priority: postfix.append(stack.pop()) stack.append(ch) postfix.extend(reversed(stack)) print(''.join(postfix)) if __name__ == '__main__': main()