forked from Blankj/awesome-java-leetcode
/
EvaluateReversePolishNotation.java
37 lines (32 loc) · 1.09 KB
/
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
package popular;
import java.util.Stack;
public class EvaluateReversePolishNotation {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
int temp = 0;
for (String s: tokens) {
if (s.equals("+")) {
temp = stack.pop() + stack.pop();
} else if (s.equals("-")) {
int right = stack.pop();
int left = stack.pop();
temp = left - right;
} else if (s.equals("*")) {
temp = stack.pop() * stack.pop();
} else if (s.equals("/")) {
int right = stack.pop();
int left = stack.pop();
temp = left / right;
} else {
temp = Integer.parseInt(s);
}
stack.push(temp);
}
return temp;
}
public static void main(String[] args) {
EvaluateReversePolishNotation obj = new EvaluateReversePolishNotation();
String[] input = {"2", "1", "+", "3", "*"};
System.out.println("ouput: " + obj.evalRPN(input));
}
}