dengch

 

最长平衡子字符串

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

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   BkDench  阅读(46)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!

导航

统计

点击右上角即可分享
微信分享提示