当前位置: 首页 > backend >正文

用栈实现+-*/计算器

lmq今天睡觉之前全文背诵一遍

leetcode224.基本计算器

class Solution {private Map<Character,Integer> map = new HashMap<>();//存储数字(如 5、10)private Deque<Character> opQue = new LinkedList<>();//存储运算符private Deque<Integer> numQue = new LinkedList<>();//定义运算符优先级private void compute(){int b = numQue.pollLast();int a = numQue.pollLast();int op = opQue.pollLast();int ans=0;switch(op){case'+': ans=a+b;break; case'-': ans=a-b;break;case'*': ans=a*b;break;case'/': ans=a/b;break;default: break;}numQue.addLast(ans);}public int calculate(String s) {s = s.replaceAll(" ","");map.put('+',0);map.put('-',0);map.put('*',1);map.put('/',1);map.put('(',-1);map.put(')',-1);numQue.addLast(0);//重要 防止负数char[] sArr = s.toCharArray();int n = sArr.length;for(int i=0;i<n;i++){// 截取数字if(sArr[i]>='0' && sArr[i]<='9'){int start = i;while(i<n && sArr[i]>='0' && sArr[i]<='9'){++i;}int num =Integer.parseInt(s.substring(start,i));numQue.addLast(num);}if(i>=n){break;}if(sArr[i]=='('){opQue.addLast(sArr[i]);}else if(sArr[i]==')'){while(opQue.peekLast()!='('){compute();}opQue.pollLast();}else{// 判断是否出现了(- 或者 (+这种情况,那么进行操作数栈补0if(i>0 && sArr[i-1]=='('){numQue.addLast(0);}//如果栈顶运算符优先级 大于等于 当前运算符,则先计算栈顶运算符。if(!opQue.isEmpty() && map.get(opQue.peekLast())>=map.get(sArr[i])){compute();}opQue.addLast(sArr[i]);}}while(!opQue.isEmpty()){compute();}return numQue.peekLast();}
}

http://www.xdnf.cn/news/6561.html

相关文章:

  • GPU八卡A100使用INT4-W4A16量化大模型实验
  • Manus AI 原理深度解析第三篇:Tools
  • 什么是DHCP?
  • JavaScript零基础入门笔记:狂神版
  • C# Try Catch Finally 执行顺序是什么?有返回值呢?
  • Openlayers:如何注册一个新的坐标系统
  • web第二次课后作业--设计一个注册登录系统
  • MyBatis:从入门到深度理解
  • 从入门到实战:时序图核心知识与高效绘制全解析(附模板)
  • 如何利用芯片模型提升终端PCB的SIPI热仿真精度
  • 如何让open-mpi在不同版本的OS上运行
  • shell常用语法
  • 晶振的核心参数
  • 会计要素+借贷分录+会计科目+账户,几个银行会计的重要概念
  • 从 Vue3 回望 Vue2:组件设计升级——Options API vs Composition API
  • OpenResty Manager 介绍与部署(Docker部署)
  • C++算法(22):二维数组参数传递,从内存模型到高效实践
  • ERP知识手册【第三弹:INV(库存管理)】
  • Windows软件插件-写mp3
  • 2021-10-25 C++三的倍数含五
  • 动态规划之数列
  • 前端缓存策略
  • 【数据结构】栈与队列
  • Redis6为什么引入了多线程?
  • 20、工业协议转换与数据采集中间件 (模拟) - /数据与物联网组件/protocol-converter-middleware
  • std::deque 底层实现结构
  • 老字号焕新案例:天猫代运营如何让传统品牌年轻化破圈
  • SEO双核驱动:关键词与长尾词优化
  • JAVA:多线程使用哈希表
  • Web前端入门:JavaScript 的应用领域