150. 逆波兰表达式求值(Medium)
题目描述
求出表 达式的值,根据 逆波兰表达式法
样例
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
题目解析
经典栈
代码
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for char in tokens:
if char in '+-*/':
x2 = stack.pop()
x1 = stack.pop()
if char == '+': stack.append(x1 + x2)
if char == '-': stack.append(x1 - x2)
if char == '*': stack.append(x1 * x2)
if char == '/': stack.append(int(x1 / x2))
else:
stack.append(int(char))
return stack[0]
Go 的使用
func Pop(nums *[]int) int {
n := len(*nums)
value := (*nums)[n - 1] // 一定要加 括号
*nums = (*nums)[:n - 1]
return value
}
func evalRPN(tokens []string) int {
n := len(tokens)
stack := make([]int, 0)
for i:= 0;i < n; i++ {
if strings.Contains("+-*/", tokens[i]) {
v1 := Pop(&stack)
v2 := Pop(&stack)
if tokens[i] == "+" {
stack = append(stack, v1 + v2)
} else if tokens[i] == "-" {
stack = append(stack, v2 - v1)
} else if tokens[i] == "*" {
stack = append(stack, v1 * v2)
} else {
stack = append(stack, v2 / v1)
}
} else {
tokenInt, _ := strconv.Atoi(tokens[i]) // value, error = strconv.Atoi
stack = append(stack, tokenInt)
}
}
return stack[0]
}
func Pop(nums *[]int) int {
n := len(*nums)
value := (*nums)[n - 1]
*nums = (*nums)[:n - 1]
return value
}
func evalRPN(tokens []string) int {
n := len(tokens)
stack := make([]int, 0)
for i:=0; i < n; i++ {
if strings.Contains("+-*/", tokens[i]){
v1 := Pop(&stack)
v2 := Pop(&stack)
if tokens[i] == "+" {
stack = append(stack, v1 + v2)
} else if tokens[i] == "-" {
stack = append(stack, v2 - v1)
} else if tokens[i] == "*" {
stack = append(stack, v1 * v2)
} else {
stack = append(stack, v2 / v1)
}
} else {
value, _ := strconv.Atoi(tokens[i])
stack = append(stack, value)
}
}
return stack[0]
}