|
| 1 | +--- |
| 2 | +comments: true |
| 3 | +difficulty: medium |
| 4 | +# Follow `Topics` tags |
| 5 | +tags: |
| 6 | + - Array |
| 7 | + - Math |
| 8 | + - Stack |
| 9 | +--- |
| 10 | + |
| 11 | +# [150. Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/description/) |
| 12 | + |
| 13 | +## Description |
| 14 | + |
| 15 | +An array of strings called `tokens`, which represents an arithmetic expression written in Reverse Polish Notation (RPN). |
| 16 | + |
| 17 | +Your task is to evaluate this expression and return the result as an integer. |
| 18 | + |
| 19 | +Keep in mind: |
| 20 | + |
| 21 | +- Valid operators include `+`, `-`, `*`, and `/`. |
| 22 | +- Each operand is either an integer or another valid RPN sub-expression. |
| 23 | +- Division between two integers should truncate toward zero. |
| 24 | +- You won't need to handle any division by zero. |
| 25 | +- The input is guaranteed to form a valid RPN expression. |
| 26 | +- Both the final result and all intermediate computations will fit within a 32-bit signed integer. |
| 27 | + |
| 28 | + |
| 29 | +**Example 1:** |
| 30 | +``` |
| 31 | +Input: tokens = ['3', '2', '+', '2', '*'] |
| 32 | +Output: 10 |
| 33 | +Explanation: (3 + 2) * 2 = 10 |
| 34 | +``` |
| 35 | + |
| 36 | +**Example 2:** |
| 37 | +``` |
| 38 | +Input: tokens = ['3', '14', '5', '/', '+'] |
| 39 | +Output: 5 |
| 40 | +Explanation: (14 / 5) + 3 = 5 |
| 41 | +``` |
| 42 | + |
| 43 | +**Constraints:** |
| 44 | + |
| 45 | +* `1 <= tokens.length <= 10^4` |
| 46 | +* `tokens[i]` is either an operator: `"+"`, `"-"`, `"*"`, or `"/"`, or an integer in the range `[-200, 200]`. |
| 47 | + |
| 48 | + |
| 49 | +## Solution |
| 50 | + |
| 51 | +This is a classic postfix expression problem. We use a stack to store operands when encountering numbers, and apply operators by popping values from the stack when an operator is found. |
| 52 | + |
| 53 | +```java |
| 54 | +class Solution { |
| 55 | + public int evalRPN(String[] tokens) { |
| 56 | + |
| 57 | + Stack<Integer> stack = new Stack<>(); |
| 58 | + for (String token : tokens) { |
| 59 | + if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) { |
| 60 | + int first = stack.pop(); |
| 61 | + int second = stack.pop(); |
| 62 | + /* In Java, when using switch with String, the compiler generates code that compares hashCode() first, then uses .equals() for exact match. This makes the average time complexity close to O(1), but the worst-case complexity is O(k), where k is the string length. Therefore, for performance-critical code, using a Map lookup or interning strings for reference comparison can be faster than a switch or chained if-else. */ |
| 63 | + if (token.equals("+")) { |
| 64 | + stack.push(second + first); |
| 65 | + } else if (token.equals("-")) { |
| 66 | + stack.push(second - first); |
| 67 | + } else if (token.equals("*")) { |
| 68 | + stack.push(second * first); |
| 69 | + } else if (token.equals("/")) { |
| 70 | + stack.push(second / first); |
| 71 | + } |
| 72 | + |
| 73 | + } else { |
| 74 | + stack.push(Integer.parseInt(token)); |
| 75 | + } |
| 76 | + } |
| 77 | + return stack.peek(); |
| 78 | + } |
| 79 | +} |
| 80 | +``` |
| 81 | + |
| 82 | +```python |
| 83 | +class Solution: |
| 84 | + def evalRPN(self, tokens: list[str]) -> int: |
| 85 | + |
| 86 | + ops = { |
| 87 | + '+': operator.add, |
| 88 | + '-': operator.sub, |
| 89 | + '*': operator.mul, |
| 90 | + '/': operator.truediv, |
| 91 | + } |
| 92 | + |
| 93 | + stack = [] |
| 94 | + for token in tokens: |
| 95 | + if token in "+-*/": |
| 96 | + first, second = stack.pop(), stack.pop() |
| 97 | + if token != "/": |
| 98 | + stack.append(ops[token](second, first)) |
| 99 | + else: |
| 100 | + stack.append(int(second / first)) |
| 101 | + else: |
| 102 | + stack.append(int(token)) |
| 103 | + return stack[0] |
| 104 | +``` |
| 105 | + |
| 106 | +## Complexity |
| 107 | + |
| 108 | +- Time complexity: $$O(n)$$ |
| 109 | +<!-- Add time complexity here, e.g. $$O(n)$$ --> |
| 110 | + |
| 111 | +- Space complexity: $$O(n)$$ |
| 112 | +<!-- Add space complexity here, e.g. $$O(n)$$ --> |
0 commit comments