dengch

 

最长平衡子字符串

题目概述:给定一字符串s(只由字符0和1组成),返回其平衡子串的最长的长度。所谓平衡子串就是指在该字串中所有的0都在1之前,且0的数量和1的数量相等
解题思路:由于数据范围比较小,所以直接暴力枚举所有子串,并判断是否为平衡子串更新答案即可。
时间复杂度\(O(n^4)\)
代码

class Solution {
    public int findTheLongestBalancedSubstring(String s) {
        int res = 0;
        int n = s.length();
        for(int i = 0; i < n; i ++){
            for(int j = i + 1; j <= n; j ++){
                String substr = s.substring(i,j);
                System.out.println(substr);
                int count0 = 0;
                int count1 = 0;
                for(int k = 0; k < substr.length(); k ++){
                    if(substr.charAt(k) == '0')count0++;
                    else count1++;
                }

                if(count0 == count1 && check(substr))res = Math.max(res,substr.length());
            }
        }
        return res;
    }

    public boolean check(String str){
        for(int i = 0; i < str.length() / 2; i ++){
            if(str.charAt(i) == '1')return false;
        }
        return true;
    }
}

posted on 2023-11-09 11:53  BkDench  阅读(19)  评论(0编辑  收藏  举报

导航