728x90
반응형

기본적인 스택 문제이다.

내가 스택 맨 처음 공부할 때 봤던 것이 후위 표기식 구현 코드였는데 이렇게 문제로 보니 반갑다!

li = list(input())
op = {'(': 0, '+':1, '-': 1, '*': 2, '/': 2, ')': 3}
stack, output = [], []
for c in li:
    if c not in op:
        output.append(c)
    elif c == '(':
        stack.append(c)    
    elif c == ')':
        while stack and stack[-1] != '(':
            output.append(stack.pop())
        stack.pop()
    else:
        while stack and op[stack[-1]] >= op[c]:
            output.append(stack.pop())
        stack.append(c)
while stack:
    output.append(stack.pop())
print(''.join(output))

 

728x90
반응형

+ Recent posts