-
Notifications
You must be signed in to change notification settings - Fork 56
/
Solution.java
34 lines (30 loc) · 1016 Bytes
/
Solution.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
package g0101_0200.s0150_evaluate_reverse_polish_notation;
// #Medium #Top_Interview_Questions #Array #Math #Stack #Programming_Skills_II_Day_3
// #2022_06_24_Time_9_ms_(51.23%)_Space_44.1_MB_(56.86%)
import java.util.Stack;
@SuppressWarnings("java:S1149")
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> st = new Stack<>();
for (String token : tokens) {
if (!Character.isDigit(token.charAt(token.length() - 1))) {
st.push(eval(st.pop(), st.pop(), token));
} else {
st.push(Integer.parseInt(token));
}
}
return st.pop();
}
private int eval(int second, int first, String operator) {
switch (operator) {
case "+":
return first + second;
case "-":
return first - second;
case "*":
return first * second;
default:
return first / second;
}
}
}