1918번: 후위 표기식

첫째 줄에 중위 표기식이 주어진다. 단 이 수식의 피연산자는 알파벳 대문자로 이루어지며 수식에서 한 번씩만 등장한다. 그리고 -A+B와 같이 -가 가장 앞에 오거나 AB와 같이 *가 생략되는 등의

www.acmicpc.net

 

더보기

연산기호만 스택에 넣는 접근은 좋았다.

근데 연산기호의 우선순위에 따라 출력할지 말지 정하는 부분은 미흡했다.

그래서 다른 블로그를 참고했다.

 

어찌저찌해서 정답의 흐름대로 잘 짰는데,

가운데 부분에 break;를 쓰지 않아서 계속 틀렸었다,,,

근데 왜 break 써야하는지 아직 잘 모르겠다.

문제 간단설명)

중위표기식을 후위표기식으로 바꾸기

 

풀이)

문자는 그대로 출력하고,

'(' 가 나오면 스택에 넣는다.

')' 가 나오면 스택에서 '(' 가 나올때까지 pop()해주고

나머지 연산기호들이 나오면 우선순위에 따라 출력하거나 스택에 넣는다.

 

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
45
46
47
48
49
import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();
        Stack<Character> stk = new Stack<>();
        String str = br.readLine();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
 
            if ('A' <= ch && ch <= 'Z') {
                sb.append(ch);
            } else if (ch == '(') {
                stk.add(ch);
            } else if (ch == ')') {
                while (!stk.isEmpty()) {
                    if (stk.peek() == '(') {
                        stk.pop();
                        break;
                    }
                    sb.append(stk.pop());
                }
            } else {
                while (!stk.isEmpty() && getPriority(stk.peek()) >= getPriority(ch)) {
                    sb.append(stk.pop());
                }
                stk.add(ch);
            }
        }
        while (!stk.isEmpty())
            sb.append(stk.pop());
        bw.write(sb.toString());
        bw.flush();
        bw.close();
    }
 
    public static int getPriority(char c) {
        if (c == '(')
            return 0;
        else if (c == '+' || c == '-')
            return 1;
        else
            return 2;
    }
}
 
 
cs

+ Recent posts