Evaluate Reverse Polish Notation
Clarification
Example
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6public class Solution {
/**
* @param tokens: The Reverse Polish Notation
* @return: the value
*/
public int evalRPN(String[] tokens) {
// write your code here
if(tokens == null || tokens.length == 0){
return 0;
}
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length ;i++ ){
if(!isOperator(tokens[i])){
stack.push(Integer.parseInt(tokens[i]));
}else{
int a = 0, b = 0;
if(stack.size() >= 2){
a = stack.pop();
b = stack.pop();
}
if(tokens[i].equals("+")){
stack.push(b+a);
}else if(tokens[i].equals("-")){
stack.push(b-a);
}else if(tokens[i].equals("*")){
stack.push(b*a);
}else if(tokens[i].equals("/")){
stack.push(b/a);
}
}
}
return stack.pop();
}
public boolean isOperator(String s){
if(s.equals("+") || s.equals("-") ||s.equals("*") || s.equals("/"))
return true;
else
return false;
}
}Last updated