【每日一题】【数栈+符号栈,考虑括号、多位数和负数】2022年2月23日-表达式求值
1、若是左括号 则ops存入
2、若是右括号 则循环找到最近的左括号 (a & b) ,再左括号之前,若有运算符,则计算;否则(及等于左括号)移除队列最后符号
3、若是运算符或者数字
3.1、若是数字,则当前下标后的所有连续数字,存入nums中,最后i重新赋值到最后连续的数字下标,如i=2, 333, j++ 后 j=5,则i=j - 1
3.2.1 若是运算符,则判断左括号、加减号是否为当前字符,若是,则存入nums为0,( -> (0; + -> 0+; - -> 0-
3.2.2 ops循环,栈内优先级大于等于当前运算符优先级,即计算
4、跳出循环,最后遍历运算符栈,计算其值
答案:
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ public int solve (String s) { // write code here if(s == null) return 0; Stack<Integer> stackInt = new Stack<>(); Stack<Character> stackOpe = new Stack<>(); int len = s.length(); for(int i = 0; i < len; i++){ if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){ if(i == 0){ stackInt.push(s.charAt(i) - '0'); }else{ //处理两位数 if(s.charAt(i-1) >= '0' && s.charAt(i-1) <= '9'){ int temp = stackInt.pop(); int number = temp * 10 + (s.charAt(i) - '0'); stackInt.push(number); }else{ stackInt.push(s.charAt(i) - '0'); } } }else{ if(stackOpe.isEmpty()){ stackOpe.push(s.charAt(i)); }else{ if(s.charAt(i) == '('){ stackOpe.push(s.charAt(i)); }else if(s.charAt(i) == ')'){ while(stackOpe.peek() != '('){ calculate(stackInt, stackOpe.pop()); } stackOpe.pop(); }else if(s.charAt(i) == '*'){ // 操作符小于或等于,都要弹出栈计算。 if(stackOpe.peek() == '*'){ calculate(stackInt, stackOpe.pop()); } stackOpe.push(s.charAt(i)); }else if(s.charAt(i) == '+' || s.charAt(i) == '-'){ if(stackOpe.peek() != '('){ calculate(stackInt, stackOpe.pop()); } stackOpe.push(s.charAt(i)); } } } } while(!stackOpe.isEmpty()){ calculate(stackInt, stackOpe.pop()); } return stackInt.peek(); } public void calculate(Stack<Integer> stackInt, char ope){ int x = stackInt.pop(); int y = stackInt.pop(); if(ope == '*'){ stackInt.push(x * y); }else if(ope == '+'){ stackInt.push(x + y); }else if(ope == '-'){ stackInt.push(y - x); } } }
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/15926030.html
分类:
算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix