当前位置:网站首页>利用“栈”快速计算——逆波兰表达式
利用“栈”快速计算——逆波兰表达式
2022-08-01 23:58:00 【陈亦康】
例题:a b c * + d e * f + g * +
对应数据:1 2 3 * + 4 5 * 6 + 7 * +
分析:(数据处理区为虚拟模块)
此时栈中剩的最后一个元素便是表达式的结果
例题:逆波兰表达式求值
由以上分析,再做此题,就容易多了~ 代码如下:
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String str : tokens){
if(judgment(str)){
int x = stack.pop();
int y = stack.pop();
switch(str){
case "+":
stack.push(y + x);
break;
case "-":
stack.push(y - x);
break;
case "*":
stack.push(y * x);
break;
case "/":
stack.push(y / x);
break;
}
}
else{
stack.push(Integer.parseInt(str));
}
}
return stack.pop();
}
private boolean judgment(String str){
if(str.equals("+") || str.equals("-") ||
str.equals("*") || str.equals("/")){
return true;
}
else{
return false;
}
}
}
边栏推荐
- Architecture basic concept and nature of architecture
- Flink学习第四天——完成第一个Flink 流批一体案例
- 如何优雅的消除系统重复代码
- C language Qixi is coming!It's time to show the romance of programmers!
- An interview question about iota in golang
- 学习英语的网站与资料
- Flink学习第三天——一文带你了解什么是Flink流?
- background-image使用
- Use Jenkins for continuous integration, this knowledge point must be mastered
- 【MySQL篇】初识数据库
猜你喜欢
WEB安全基础 - - - XRAY使用
The Spark of Sql join on the and and where
20220725资料更新
security CSRF漏洞保护
@WebServlet注解(Servlet注解)
Work for 5 years, test case design is bad?To look at the big case design summary
Keepalived 高可用的三种路由方案
Flink Yarn Per Job - CliFrontend
企业防护墙管理,有什么防火墙管理工具?
Deliver cloud-native microservices applications with Zadig
随机推荐
【图像融合】基于加权和金字塔实现图像融合附matlab代码
An interview question about iota in golang
1个月写900多条用例,二线城市年薪33W+的测试经理能有多卷?
【MySQL篇】初识数据库
security cross-domain configuration
类型“FC<Props>”的参数不能赋给类型“ForwardRefRenderFunction<unknown, Props>”的参数。 属性“defaultProps”的类型不兼容。 不
Win11如何获得最佳电源效率?
security CSRF漏洞保护
Flink Yarn Per Job - Yarn应用
为什么要使用MQ消息中间件?这几个问题必须拿下
Artifact XXXwar exploded Artifact is being deployed, please wait...(已解决)
一道golang中关于iota的面试题
CDH6 Hue to open a "ASCII" codec can 't encode characters
C语言七夕来袭!是时候展现专属于程序员的浪漫了!
2022第六届强网杯部分wp
yay 报错 response decoding failed: invalid character ‘<‘ looking for beginning of value;
Excel表格数据导入MySQL数据库
GetHashCode与Equals
【三子棋】C语言实现简易三子棋
辛普森悖论