原题
https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/
思路
栈
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token in ['+', '-', '*', '/']:
y = stack.pop()
x = stack.pop()
if token == '+':
stack.append(x + y)
elif token == '-':
stack.append(x - y)
elif token == '*':
stack.append(x * y)
else:
d, m = divmod(x, y)
if d >= 0:
stack.append(d)
elif d < 0 and m == 0:
stack.append(d)
else:
stack.append(d + 1)
else:
stack.append(int(token))
return stack[0]
Go代码
func evalRPN(tokens []string) int {
stack := []int{}
for _, token := range tokens {
if token == "+" || token == "-" || token == "*" || token == "/" {
y := stack[len(stack)-1]
x := stack[len(stack)-2]
stack = stack[:len(stack)-2]
if token == "+" {
stack = append(stack, x+y)
} else if token == "-" {
stack = append(stack, x-y)
} else if token == "*" {
stack = append(stack, x*y)
} else {
stack = append(stack, x/y)
}
} else {
i, err := strconv.Atoi(token)
if err != nil {
fmt.Println("error: ", err)
}
stack = append(stack, i)
}
}
return stack[0]
}
1301

被折叠的 条评论
为什么被折叠?



