当前位置:网站首页>利用“栈”快速计算——逆波兰表达式
利用“栈”快速计算——逆波兰表达式
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;
}
}
}
边栏推荐
- 切面打印调取的方法
- 【Leetcode】470. Implement Rand10() Using Rand7()
- Flink Yarn Per Job - Yarn应用
- 多御安全浏览器android版更新至1.7,改进加密协议
- cdh6 opens oozieWeb page, Oozie web console is disabled.
- UI自动化测试框架搭建-标记性能较差用例
- GIF制作-灰常简单的一键动图工具
- @Scheduled注解详解
- FAST-LIO2代码解析(二)
- Use Jenkins for continuous integration, this knowledge point must be mastered
猜你喜欢

【MySQL系列】MySQL数据库基础

在MySQL登录时出现Access denied for user ‘root‘@‘localhost‘ (using password YES) 拒绝访问问题解决

Spark Sql之join on and和where

为什么要使用MQ消息中间件?这几个问题必须拿下

TCP 可靠吗?为什么?

How to reinstall Win11?One-click method to reinstall Win11

Various Joins of Sql

【MySQL系列】 MySQL表的增删改查(进阶)

security跨域配置

cdh6打开oozieWeb页面,Oozie web console is disabled.
随机推荐
【ACWing】406. 放置机器人
Convert LocalDateTime to Date type
@Transactional 注解使用详解
使用Jenkins做持续集成,这个知识点必须要掌握
TCP 可靠吗?为什么?
Flink学习第五天——Flink可视化控制台依赖配置和界面介绍
Deliver cloud-native microservices applications with Zadig
如何重装Win11?一键重装Win11方法
带你搞懂MySQL隔离级别,两个事务同时操作同一行数据会怎样?
【MySQL系列】 MySQL表的增删改查(进阶)
cdh6打开oozieWeb页面,Oozie web console is disabled.
Wincc报表教程(SQL数据库的建立,wincc在数据库中保存和查询数据,调用Excel模板把数据保存到指定的位置和打印功能)
Flink学习第三天——一文带你了解什么是Flink流?
多御安全浏览器android版更新至1.7,改进加密协议
yay 报错 response decoding failed: invalid character ‘<‘ looking for beginning of value;
Artifact XXXwar exploded Artifact is being deployed, please wait...(已解决)
在MySQL中使用MD5加密【入门体验】
在CDH的hue上的oozie出现,提交 Coordinator My Schedule 时出错
在MySQL登录时出现Access denied for user ‘root‘@‘localhost‘ (using password YES) 拒绝访问问题解决
Study Notes: The Return of Machine Learning