leetcode 6038. 向表达式添加括号后的最小结果 java

https://leetcode-cn.com/problems/minimize-result-by-adding-parentheses-to-expression/
枚举左括号右括号位置

class Solution {
    public String minimizeResult(String expression) {
        int plus=expression.indexOf("+");
        String res="";
        int min=Integer.MAX_VALUE;
        for(int left=0;left<plus;left++){
            for(int right=plus+1;right<expression.length();right++){
                String s1=expression.substring(0,left);
                String s2=expression.substring(left,right+1);
                String s3=expression.substring(right+1,expression.length());
                int cur=cal(s1,s2,s3);
                if(cur<min){
                    min=cur;
                    //return String.valueOf(min);
                    res=String.format("%s(%s)%s",s1,s2,s3);
                }
            }
        }
        return res;
    }
    public int cal(String s1,String s2,String s3){
        String[] sp=s2.split("\\+");
        int num2=0;
        for(String s:sp){
            num2+=Integer.parseInt(s);
        }
        if(!s1.isEmpty()){
            num2*=Integer.parseInt(s1);
        }
        if(!s3.isEmpty()){
            num2*=Integer.parseInt(s3);
        }
        return num2;
    }
}

你可能感兴趣的:(LeetCode,leetcode)