-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path150.java
More file actions
53 lines (51 loc) · 1.77 KB
/
150.java
File metadata and controls
53 lines (51 loc) · 1.77 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
__________________________________________________________________________________________________
sample 1 ms submission
class Solution {
private String[] tokens;
private int index;
public int evalRPN(String[] tokens) {
this.tokens = tokens;
this.index = tokens.length -1;
return eval();
}
private int eval() {
String token = tokens[index--];
if ("+".equals(token)) return eval() + eval();
else if ("-".equals(token)) return -eval() + eval();
else if ("*".equals(token)) return eval() * eval();
else if ("/".equals(token)) {
int divisor = eval();
return eval() / divisor;
}
return Integer.parseInt(token);
}
}
__________________________________________________________________________________________________
sample 34192 kb submission
class Solution {
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0){
return 0;
}
Stack<Integer> stack = new Stack<>();
for (String s : tokens){
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
int b = stack.pop();
int a = stack.pop();
if (s.equals("+")){
stack.push(a+b);
}else if (s.equals("-")){
stack.push(a-b);
}else if (s.equals("*")){
stack.push(a*b);
}else if (s.equals("/")){
stack.push(a/b);
}
}else{
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}
__________________________________________________________________________________________________