每日一题2609. 最长平衡子字符串

每日一题2609. 最长平衡子字符串

LeetCode题目:https://leetcode.cn/problems/find-the-longest-balanced-substring-of-a-binary-string/

滑动窗口暴力解法

  直接构建n长度的字符串,使其符合000111的规律,然后滑动进行匹配。。

代码如下:

class Solution {
    public int findTheLongestBalancedSubstring(String s) {
        int result = 0;
        for (int i = 2; i <= s.length(); i+=2) {
            String check = "";
            for (int k = 0; k < i; k++) {
                if (k < i /2) {
                    check = check + '0';
                }else {
                    check = check + '1';
                }
            }
            for (int j = 0; j <= s.length() - i; j++) {
                String temp = s.substring(j, j + i);
                if (temp.equals(check)) {
                    result = i;
                }
            }
        }

        return result;
    } 
}

  因为每次都需要构建一个n长度的字符串,然后再进行逐个比较,因此十分暴力耗时间。

  因此,发现规律可以通过对0和1两个字符分别进行计数来进行计算,可以分为几种情况:

1、如果当前字符为0,则正常进行计数。

2、当前字符为1,则说明当前计数结束,由于字符串要根据0和1的最少数目来进行构建(“0000111”肯定是按照1的长度来构建,“001111”肯定以0的长度来计算),所以计算结果为min(result, 2 * min(count[0],count[1])).

3、当字符为0,且上一个字符为1的时候,说明当前计数的字符串已经不是平衡字符串了,因此清空前面的数据置零,并count[0]+1;

  因此代码如下:

class Solution {
    public int findTheLongestBalancedSubstring(String s) {
        int result = 0;
        int len = s.length();
        int[] count = new int[2];
        for (int i = 0; i < len; i++) {
            if (s.charAt(i) == '1') {
                count[1]++;
                result = Math.max(result, 2*Math.min(count[0],count[1]));
            }else if (i != 0 && s.charAt(i - 1) == '1') {
                count[1] = 0;
                count[0] = 1;
            }else if (s.charAt(i) == '0') {
                count[0]++;
            }
        }

        return result;
    } 
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值