forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_150.java
37 lines (34 loc) · 1.22 KB
/
_150.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 com.fishercoder.solutions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
public class _150 {
public static class Solution1 {
public int evalRPN(String[] tokens) {
Set<String> operators = new HashSet<>(Arrays.asList("+", "-", "*", "/"));
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (operators.contains(token)) {
int secondNum = stack.pop();
int firstNum = stack.pop();
int result;
if (token.equals("+")) {
result = firstNum + secondNum;
} else if (token.equals("-")) {
result = firstNum - secondNum;
} else if (token.equals("*")) {
result = firstNum * secondNum;
} else {
result = firstNum / secondNum;
}
stack.push(result);
} else {
int num = Integer.parseInt(token);
stack.push(num);
}
}
return stack.pop();
}
}
}