-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMain.java
38 lines (31 loc) Β· 1.19 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
package Stack.P1918;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
static String s, ops = "+-*/";
static Stack<Character> stack;
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("src/Stack/P1918/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
stack = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int i = 0, len = s.length(); i < len; i++) {
char c = s.charAt(i);
if ('A' <= c && c <= 'Z') sb.append(c);
else if (c == '(') stack.push(c);
else if (c == ')') {
char op;
while ((op = stack.pop()) != '(') sb.append(op);
} else {
while (!stack.isEmpty() && stack.peek() != '(' &&
ops.indexOf(stack.peek()) / 2 >= ops.indexOf(c) / 2) sb.append(stack.pop());
stack.push(c);
}
}
while (!stack.isEmpty()) sb.append(stack.pop());
System.out.println(sb);
}
}