본문 바로가기

00/algorithm

백준 1918번 후위표기식 (Python)

반응형

문제


https://www.acmicpc.net/problem/1918


풀이


스택의 가장 위에있는 요소보다 우선순위가 낮은 연산자가 들어오면 스택을 비운다. 괄호를 만나면 괄호를 닫을 수 있을 때까지 스택을 비운다.

어제 푼 문제인데 오늘 그래픽스 수업에서 교수님이 말하셔서 놀랬다.. 역시 자료구조가 기본이다~



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def priority(x) :
 
    if x == "*" or x == "/" :
        return 2
    elif x == "+" or x == "-" :
        return 1
    elif x == "(" or x == ")" :
        return 0
 
    return -1
 
def solve() :
 
    X = input()
 
    ans = ""
    stack = []
 
    for c in X :

        p = priority(c)
        
        if c == '+' or c == '-' or c == '*' or c == '/':
            while stack and priority(stack[-1]) >= p :
                ans += stack.pop()
            stack.append(c)
            continue
        elif c == '(' :
            stack.append(c)
            continue
        elif c == ')' :
            while stack and stack[-1!= "(" :
                ans += stack.pop()
            stack.pop()
            continue
 
        ans += c
 
    while stack :
        ans += stack.pop()
    print(ans)
 
solve()
cs


반응형