-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.java
50 lines (46 loc) · 1.16 KB
/
Main.java
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
50
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
int[] opPriority = new int[50];
private void init() {
opPriority['*'] = opPriority['/'] = 1;
opPriority['('] = opPriority[')'] = -1;
}
private void solution() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
init();
String s = br.readLine();
StringBuilder sb = new StringBuilder();
Stack<Character> stk = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'A') {
sb.append(c);
continue;
}
if (c == '(') {
stk.add(c);
continue;
}
if (c == ')') {
while (stk.peek() != '(') {
sb.append(stk.pop());
}
stk.pop();
continue;
}
while (!stk.isEmpty() && opPriority[stk.peek()] >= opPriority[c]) {
sb.append(stk.pop());
}
stk.add(c);
}
while (!stk.isEmpty()) {
sb.append(stk.pop());
}
System.out.println(sb);
}
public static void main(String[] args) throws Exception {
new Main().solution();
}
}