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);
    }
}
相关推荐
苦瓜汤补钙32 分钟前
论文阅读:3D Gaussian Splatting for Real-Time Radiance Field Rendering
论文阅读·人工智能·算法·3d
LNTON羚通1 小时前
明烟明火检测算法、烟火检测、森林防火检测
大数据·网络·人工智能·算法·音视频
MogulNemenis2 小时前
力扣100题——技巧
算法·leetcode
每天瞎忙的农民工2 小时前
PHP常用的几种算法
算法·php
175063319452 小时前
Matlab/Simulink中PMSM模型的反电动势系数和转矩系数
算法·机器学习·matlab
岸边的风2 小时前
前端Excel热成像数据展示及插值算法
前端·算法·excel
wheeldown3 小时前
【C语言】(指针系列3)数组指针+函数指针+typedef+函数数组指针+转移表
c语言·数据结构·算法
小比卡丘4 小时前
C语言进阶版第8课—指针(2)
c语言·开发语言·算法
NeVeRMoRE_20244 小时前
【数据结构和算法实践-树-LeetCode107-二叉树的层序遍历Ⅱ】
数据结构·算法·leetcode
2301_778411944 小时前
数据结构----树
数据结构·算法