-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution227.java
More file actions
70 lines (68 loc) · 2.11 KB
/
Solution227.java
File metadata and controls
70 lines (68 loc) · 2.11 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Stack;
/**
* Created by Alex on 2016/5/19.
*/
public class Solution227 {
public int calculate(String s) {
String RPNString = getRPN(s);
String[] data = RPNString.split(" ");
Stack<Integer> stack = new Stack<>();
for(String element : data){
if(element.equals("+") || element.equals("-") || element.equals("*") || element.equals("/")){
int a = stack.pop();
int b = stack.pop();
switch (element){
case "+":
stack.push(a+b);
break;
case "-":
stack.push(b-a);
break;
case "*":
stack.push(a*b);
break;
case "/":
stack.push(b/a);
break;
}
}else{
stack.push(Integer.parseInt(element));
}
}
return stack.pop();
}
public String getRPN(String s){
Stack<Character> stack = new Stack<>();
char[] input = s.toCharArray();
StringBuilder sb = new StringBuilder();
for(char c : input){
if(c ==' '){
continue;
}
if(c>='0' && c<='9'){
sb.append(c);
}else {
sb.append(" ");
if(c=='*' || c=='/'){
while(!stack.isEmpty() && (stack.peek() == '*' || stack.peek() == '/')){
sb.append(stack.pop());
sb.append(" ");
}
stack.push(c);
}
if(c=='+' || c=='-'){
while(!stack.isEmpty()){
sb.append(stack.pop());
sb.append(" ");
}
stack.push(c);
}
}
}
while(!stack.isEmpty()){
sb.append(" ");
sb.append(stack.pop());
}
return sb.toString();
}
}