Leetcode 150. Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation (RPN).
Valid operators are +
, -
, *
, and /
. Each operand may be an integer or another expression.
Note:
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
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
+
, -
, *
, and /
?
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
switch (token) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
int b = stack.pop();
int a = stack.pop();
stack.push(a - b);
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
b = stack.pop();
a = stack.pop();
stack.push(a / b);
break;
default:
stack.push(Integer.parseInt(token));
break;
}
}
return stack.pop();
}
// Example Usage
public static void main(String[] args) {
Solution solution = new Solution();
String[] tokens1 = {"2", "1", "+", "3", "*"};
System.out.println(solution.evalRPN(tokens1)); // Output: 9
String[] tokens2 = {"4", "13", "5", "/", "+"};
System.out.println(solution.evalRPN(tokens2)); // Output: 6
String[] tokens3 = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
System.out.println(solution.evalRPN(tokens3)); // Output: 22
}
}
The time complexity of this algorithm is O(n), where n
is the number of tokens in the input list. Each token is processed exactly once. The stack operations (push and pop) are O(1), so the overall complexity is linear in terms of the number of tokens.
The space complexity is also O(n) due to the space used by the stack to store the operands.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?