-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode150.java
More file actions
45 lines (41 loc) · 1.62 KB
/
LeetCode150.java
File metadata and controls
45 lines (41 loc) · 1.62 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
import java.util.Stack;
public class LeetCode150 {
public static void main(String[] args) {
String[] tokens1 = new String[] { "2", "1", "+", "3", "*" };
System.out.println(new Solution150().evalRPN(tokens1));
String[] tokens2 = new String[] { "4", "13", "5", "/", "+" };
System.out.println(new Solution150().evalRPN(tokens2));
String[] tokens3 = new String[] { "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" };
System.out.println(new Solution150().evalRPN(tokens3));
}
}
class Solution150 {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")) {
Integer secondInt = stack.pop();
Integer firstInt = stack.pop();
switch (tokens[i]) {
case "+":
stack.push(firstInt + secondInt);
break;
case "-":
stack.push(firstInt - secondInt);
break;
case "*":
stack.push(firstInt * secondInt);
break;
case "/":
stack.push(firstInt / secondInt);
break;
default:
break;
}
} else {
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}