Evaluate Reverse Polish Notation
You are given an array of strings tokens
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
-
The valid operators are
,'+' ,'-' , and'*' .'/' - Each operand may be an integer or another expression.
- The division between two integers always truncates toward zero.
- There will not be any division by zero.
- The input represents a valid arithmetic expression in a reverse polish notation.
- The answer and all the intermediate calculations can be represented in a 32-bit integer.
Example 1
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
Constraints:
1 <= tokens.length <= 104 is either an operator:tokens[i] ,"+" ,"-" , or"*" , or an integer in the range"/" .[-200, 200]
Contents
Solution 1 - Using stack
First, let's understand this Reverse Polish Notation (RPN), in this notation we will have a list of operands and operators, when an operator is occurred,
we ned to apply that operator on two left most operands. For example, consider this notation "4","13","5","/","+"'/'13/5 = 2"4", "2", "+"'+'4+2 = 6
In this approach, we are going to add elements into a Stack
import java.util.Stack;
public class ReversePolishNotation {
static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String token: tokens) {
if("+".equals(token)) {
int x1 = stack.pop();
int x2 = stack.pop();
stack.push(x2+x1);
} else if("-".equals(token)) {
int x1 = stack.pop();
int x2 = stack.pop();
stack.push(x2-x1);
} else if("*".equals(token)) {
int x1 = stack.pop();
int x2 = stack.pop();
stack.push(x2*x1);
} else if("/".equals(token)) {
int x1 = stack.pop();
int x2 = stack.pop();
stack.push(x2/x1);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
public static void main(String[] args) {
System.out.println(evalRPN(new String[]{"2","1","+","3","*"}));
System.out.println(evalRPN(new String[]{"4","13","5","/","+"}));
System.out.println(evalRPN(new String[]{"10","6","9","3","+","-11","*","/","*","17","+","5","+"}));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time.
Space complexity: O(n).
Above implementations source code can be found at