当前位置:网站首页>利用“栈”快速计算——逆波兰表达式
利用“栈”快速计算——逆波兰表达式
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;
}
}
}
边栏推荐
猜你喜欢
12306抢票,极限并发带来的思考?
ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation
ICLR 2022最佳论文:基于对比消歧的偏标签学习
QML package management
How to solve the error when mysql8 installs make
Wincc报表教程(SQL数据库的建立,wincc在数据库中保存和查询数据,调用Excel模板把数据保存到指定的位置和打印功能)
security cross-domain configuration
如何进行数据库备份
Axure教程-新手入门基础(小白强烈推荐!!!)
Win11如何获得最佳电源效率?
随机推荐
ICLR 2022最佳论文:基于对比消歧的偏标签学习
如何进行数据库备份
【图像融合】基于加权和金字塔实现图像融合附matlab代码
学习英语的网站与资料
在CentOS下安装MySQL
solidity
获取小猪民宿(短租)数据
FAST-LIO2 code analysis (2)
Detailed explanation of Zadig's self-testing and tuning environment technical solution for developers
Classical Literature Reading--DLO
Deliver cloud-native microservices applications with Zadig
Get piggy homestay (short-term rental) data
【Leetcode】2360. Longest Cycle in a Graph
【MySQL系列】MySQL索引事务
如何用Redis实现分布式锁?
Enterprise firewall management, what firewall management tools are there?
OpenCV DNN blogFromImage()详解
security跨域配置
检查 Oracle 版本的 7 种方法
@Scheduled注解详解