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);
    }
}
相关推荐
渐暖°6 分钟前
【leetcode算法从入门到精通】5. 最长回文子串
vscode·算法·leetcode
今天_也很困6 分钟前
LeetCode热题100-560. 和为 K 的子数组
java·算法·leetcode
v_for_van19 分钟前
力扣刷题记录2(无算法背景,纯C语言)
c语言·算法·leetcode
2301_8112329825 分钟前
低延迟系统C++优化
开发语言·c++·算法
alphaTao26 分钟前
LeetCode 每日一题 2026/1/26-2026/2/1
算法·leetcode
向哆哆43 分钟前
构建跨端健身俱乐部管理系统:Flutter × OpenHarmony 的数据结构与设计解析
数据结构·flutter·鸿蒙·openharmony·开源鸿蒙
Christo31 小时前
TFS-2026《Fuzzy Multi-Subspace Clustering 》
人工智能·算法·机器学习·数据挖掘
2401_857683541 小时前
C++中的原型模式
开发语言·c++·算法
s1hiyu1 小时前
C++动态链接库开发
开发语言·c++·算法
(❁´◡`❁)Jimmy(❁´◡`❁)1 小时前
CF2188 C. Restricted Sorting
c语言·开发语言·算法