原题
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.
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
解法
stack. 构造nums列表存放数字, 遍历tokens, 如果是数字, 那么把它放到nums里, 如果是运算符号, 那么提取最后两个数字进行运算后, 再放进nums. 注意题目要求整除相除时向0取整, 那么当整除结果为负且无法除尽时, 例如:在python里, -4//3 = -2, 此时我们需要加1得出符合题意的结果.
Time: O(n)
Space: O(n)
代码
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
nums = []
for token in tokens:
if token.isdigit() or token.lstrip('-').isdigit():
nums.append(int(token))
elif token == '+':
ans = nums.pop() + nums.pop()
nums.append(ans)
elif token == '-':
last = nums.pop()
first = nums.pop()
ans = first - last
nums.append(ans)
elif token == '*':
ans = nums.pop() * nums.pop()
nums.append(ans)
elif token == '/':
last = nums.pop()
first = nums.pop()
ans = first // last
if ans < 0 and first % last != 0:
ans += 1
nums.append(ans)
return nums[0]