-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path150.逆波兰表达式求值.py
More file actions
81 lines (78 loc) · 2.03 KB
/
150.逆波兰表达式求值.py
File metadata and controls
81 lines (78 loc) · 2.03 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#
# @lc app=leetcode.cn id=150 lang=python
#
# [150] 逆波兰表达式求值
#
# https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/description/
#
# algorithms
# Medium (46.11%)
# Likes: 66
# Dislikes: 0
# Total Accepted: 14.9K
# Total Submissions: 32.3K
# Testcase Example: '["2","1","+","3","*"]'
#
# 根据逆波兰表示法,求表达式的值。
#
# 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
#
# 说明:
#
#
# 整数除法只保留整数部分。
# 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
#
#
# 示例 1:
#
# 输入: ["2", "1", "+", "3", "*"]
# 输出: 9
# 解释: ((2 + 1) * 3) = 9
#
#
# 示例 2:
#
# 输入: ["4", "13", "5", "/", "+"]
# 输出: 6
# 解释: (4 + (13 / 5)) = 6
#
#
# 示例 3:
#
# 输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
# 输出: 22
# 解释:
# ((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
#
#
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for t in tokens:
if t not in ["+", "-", "*", "/"]:
stack.append(int(t))
else:
r, l = stack.pop(), stack.pop()
if t == "+":
stack.append(l+r)
elif t == "-":
stack.append(l-r)
elif t == "*":
stack.append(l*r)
else:
# python的 b / a 会向下取整, 比如 -1 / 132 = -1。
#题目要求是取整数部分,那么负数的时候,实际应该是向上取整
# 解决方法: int(b / float(a))
stack.append(int(l/float(r)))
return stack.pop()