LeetCode #150 Evaluate Reverse Polish Notation

Problem

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Examples

1
2
3
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
1
2
3
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
1
2
3
4
5
6
7
8
9
10
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

Boundary Conditions

  • Will there be any divided by zero operation?
  • Can the given RPN expression be wrong?
    • Not matched
    • Expression includes invalid characters

Solution

Method:

Time Complexity:

Space Complexity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
if len(tokens) == 1:
return int(tokens.pop())

val = 0
stack = []
operators = set(['+', '-', '*', '/'])

for token in tokens:
if token not in operators:
stack.append(token)
else:
l2 = int(stack.pop())
l1 = int(stack.pop())
if token == '+':
val = l1 + l2
elif token == '-':
val = l1 - l2
elif token == '*':
val = l1 * l2
elif token == '/':
val = int(l1 / l2)

stack.append(str(val))

return val

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
operators = {'+': lambda x, y: x + y, \
'-': lambda x, y: x - y, \
'*': lambda x, y: x * y, \
'/': lambda x, y: int(x/y)}

for token in tokens:
if token not in operators:
stack.append(token)
else:
l2 = int(stack.pop())
l1 = int(stack.pop())
val = operators[token](l1, l2)
stack.append(str(val))

return int(stack.pop())