BM49 表达式求值

java 复制代码
import java.util.*;
public class Solution {
    public ArrayList<Integer> function(String s, int index){
        Stack<Integer> stack = new Stack<Integer>(); 
        int num = 0;
        char op = '+';
        int i;
        for(i = index; i < s.length(); i++){
            if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){ 
                num = num * 10 + s.charAt(i) - '0';
                if(i != s.length() - 1)
                    continue;
            }
            if(s.charAt(i) == '('){
                ArrayList<Integer> res = function(s, i + 1);
                num = res.get(0);
                i = res.get(1);
                if(i != s.length() - 1)
                    continue;
            }            
            switch(op){
            case '+': 
                stack.push(num);
                break;
            case '-':
                stack.push(-num);
                break;
            case '*':  
                int temp = stack.pop();
                stack.push(temp * num);
                break;
            }
            num = 0;
            if(s.charAt(i) == ')') 
                break; 
            else 
                op = s.charAt(i);
        }
        int sum = 0;
        while(!stack.isEmpty())  
            sum += stack.pop();
        ArrayList<Integer> temp = new ArrayList<Integer>();
        temp.add(sum);
        temp.add(i);
        return temp; 
    }
    public int solve (String s) {
        ArrayList<Integer> res = function(s, 0);
        return res.get(0);
    }
}
相关推荐
无敌最俊朗@4 分钟前
力扣hot100-环形链表(2)142
算法·leetcode·链表
Elias不吃糖43 分钟前
LeetCode每日一练(189, 122)
c++·算法·leetcode
w***37511 小时前
SpringMVC 请求参数接收
前端·javascript·算法
小猪咪piggy1 小时前
【算法】day 19 leetcode 100 矩阵+贪心
算法·leetcode·矩阵
-森屿安年-1 小时前
LeetCode 11. 盛最多水的容器
开发语言·c++·算法·leetcode
flashlight_hi1 小时前
LeetCode 分类刷题:112. 路径总和
javascript·算法·leetcode
努力学习的小廉2 小时前
我爱学算法之—— 多源BFS
算法·宽度优先
@卞2 小时前
高阶数据结构 --- 单调栈
数据结构
WWZZ20253 小时前
快速上手大模型:深度学习11(数据增强、微调、目标检测)
人工智能·深度学习·算法·目标检测·计算机视觉·大模型·具身智能
fashion 道格3 小时前
深入理解队列的艺术
数据结构·算法