-
Notifications
You must be signed in to change notification settings - Fork 0
/
150_EvaluateReversePolishNotation.java
76 lines (74 loc) · 2.32 KB
/
150_EvaluateReversePolishNotation.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* Evaluate the value of an arithmetic expression in Reverse Polish Notation.
* Valid operators are +, -, *, /. Each operand may be an integer or another expression.
* Some examples:
* ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
* ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
//规范
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String token : tokens) {
if(!isSign(token)) {
stack.push(Integer.parseInt(token));
} else {
int r = stack.pop();
int l = stack.pop();
int res = 0;
res = select(token, l, r, res);
stack.push(res);
}
}
return stack.isEmpty() ? 0 : stack.pop();
}
private int select(String s, int l, int r, int res) {
switch(s) {
case "+" : res = l + r;
break;
case "-" : res = l - r;
break;
case "*" : res = l * r;
break;
case "/" : res = l / r;
break;
default : res = 0;
break;
}
return res;
}
private boolean isSign(String s) {
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
return true;
}
return false;
}
}
//
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for(int i=0; i<tokens.length; i++) {
if(tokens[i].equals("+")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b + a);
} else if(tokens[i].equals("-")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b - a);
} else if(tokens[i].equals("*")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b * a);
} else if(tokens[i].equals("/")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b / a);
} else {
stack.push(Integer.valueOf(tokens[i]));
}
}
return stack.pop();
}
}