Problem
https://leetcode.com/problems/evaluate-reverse-polish-notation/
Solution
class Solution {
Set<String> operator = new HashSet<>();
Stack<String> stack = new Stack<>();
public int evalRPN(String[] tokens) {
operator.add("+");
operator.add("-");
operator.add("*");
operator.add("/");
int result = 0;
for (int i=0;i<tokens.length;i++) {
String token = tokens[i];
if (operator.contains(token)) {
int a = Integer.parseInt(stack.pop());
int b = Integer.parseInt(stack.pop());
if ("+".equals(token)) {
stack.push(String.valueOf(a + b));
} else if ("-".equals(token)) {
stack.push(String.valueOf(b - a));
} else if ("*".equals(token)) {
stack.push(String.valueOf(a * b));
} else if ("/".equals(token)) {
stack.push(String.valueOf(b / a));
}
} else {
stack.push(token);
}
}
result = Integer.parseInt(stack.pop());
return result;
}
}

Leave a comment