每日一题 --- 逆波兰表达式求值[力扣][Go]

150. 逆波兰表达式求值

题目:150. 逆波兰表达式求值

给你一个字符串数组 tokens ,表示一个根据 逆波兰表示法 表示的算术表达式。

请你计算该表达式。返回一个表示表达式值的整数。

注意:

  • 有效的算符为 '+''-''*''/'
  • 每个操作数(运算对象)都可以是一个整数或者另一个表达式。
  • 两个整数之间的除法总是 向零截断
  • 表达式中不含除零运算。
  • 输入是一个根据逆波兰表示法表示的算术表达式。
  • 答案及所有中间计算结果可以用 32 位 整数表示。

示例 1:

复制代码
输入:tokens = ["2","1","+","3","*"]
输出:9
解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9

示例 2:

复制代码
输入:tokens = ["4","13","5","/","+"]
输出:6
解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6

示例 3:

复制代码
输入:tokens = ["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

提示:

  • 1 <= tokens.length <= 104
  • tokens[i] 是一个算符("+""-""*""/"),或是在范围 [-200, 200] 内的一个整数

逆波兰表达式:

逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。

  • 平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 )
  • 该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * )

逆波兰表达式主要有以下两个优点:

  • 去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。
  • 适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中

方法一:

后缀表达式可以使用栈求解。

go 复制代码
func evalRPN(tokens []string) int {
	stack := []string{}
	for _, token := range tokens {
		switch token {
		case "+":
			t1 := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			t2 := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			n1, _ := strconv.Atoi(t1)
			n2, _ := strconv.Atoi(t2)
			stack = append(stack, strconv.Itoa(n2+n1))

		case "-":
			t1 := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			t2 := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			n1, _ := strconv.Atoi(t1)
			n2, _ := strconv.Atoi(t2)
			stack = append(stack, strconv.Itoa(n2-n1))

		case "*":
			t1 := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			t2 := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			n1, _ := strconv.Atoi(t1)
			n2, _ := strconv.Atoi(t2)
			stack = append(stack, strconv.Itoa(n2*n1))

		case "/":
			t1 := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			t2 := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			n1, _ := strconv.Atoi(t1)
			n2, _ := strconv.Atoi(t2)
			stack = append(stack, strconv.Itoa(n2/n1))
		default:
			stack = append(stack, token)
		}
	}
	atoi, _ := strconv.Atoi(stack[0])
	return atoi
}
相关推荐
jiayou641 天前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
李广坤2 天前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
爱可生开源社区3 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1773 天前
《从零搭建NestJS项目》
数据库·typescript
花酒锄作田3 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
加号34 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏4 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐4 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
百锦再4 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip