做一个general 的改动,因为有时候会有多于三个括号的情况,类似与(((())))。

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        String s1 = str.replace("[","(");
        String s2 = s1.replace("]",")");
        String s3 = s2.replace("{","(");
        String s4 = s3.replace("}",")");
        int res = solve(s4);
        System.out.println(res);
    }

    public static int solve(String s){
        if(s==null||s.length()==0) return 0;
        Stack<Integer> stack = new Stack<>();
        int number = 0;
        int len = s.length();
        char sign = '+';
        char[] chs = s.toCharArray();
        for(int i=0;i<len;i++){
            char c = chs[i];
            if(c==' ') continue;
            if(Character.isDigit(c)){
                number = number*10+c-'0';
            }
            if(c=='('){
                int j=i+1, counter=1;
                while(counter>0){
                    if(chs[j]=='(') counter++;
                    if(chs[j]==')') counter--;
                    j++;
                }
                number = solve(s.substring(i+1,j-1));
                i=j-1;
            }
            if(!Character.isDigit(c)||i==len-1){
                if(sign=='+'){
                    stack.push(number);
                }else if(sign=='-'){
                    stack.push(-1*number);
                }else if(sign=='*'){
                    stack.push(stack.pop()*number);
                }else if(sign=='/'){
                    stack.push(stack.pop()/number);
                }
                number = 0;
                sign = c;
            }
        }
        int ans = 0;
        while(!stack.isEmpty()){
            ans+=stack.pop();
        }
        return ans;
    }
}