LeetCode每日一题——2609. Find the Longest Balanced Substring of a Binary String

文章目录

一、题目

You are given a binary string s consisting only of zeroes and ones.

A substring of s is considered balanced if all zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.

Return the length of the longest balanced substring of s.

A substring is a contiguous sequence of characters within a string.

Example 1:

Input: s = "01000111"

Output: 6

Explanation: The longest balanced substring is "000111", which has length 6.

Example 2:

Input: s = "00111"

Output: 4

Explanation: The longest balanced substring is "0011", which has length 4.

Example 3:

Input: s = "111"

Output: 0

Explanation: There is no balanced substring except the empty substring, so the answer is 0.

Constraints:

1 <= s.length <= 50

'0' <= si <= '1'

二、题解

cpp 复制代码
class Solution {
public:
    int findTheLongestBalancedSubstring(string s) {
        int n = s.length();
        int res = 0;
        for(int i = 0;i < n;i++){
            //过滤到字符串最前面的1
            if(s[i] - '0' == 1) continue;
            int zeroCount = 0;
            int oneCount = 0;
            //统计0的数量
            while(s[i] - '0' == 0 && i < n) zeroCount++,i++;
            //统计1的数量
            while(s[i] - '0' == 1 && i < n) oneCount++,i++;
            i--;
            res = max(res,min(zeroCount,oneCount) * 2);
        }
        return res;
    }
};
相关推荐
Thomas214311 分钟前
spark sort shuffer 和 hash shuffer 图解对比
算法·哈希算法
Zixhy12 分钟前
Boost 库实现异步高并发服务器
linux·服务器·c++
AbandonForce30 分钟前
简谈线程池
开发语言·c++·算法
智购科技智能售货柜40 分钟前
2026自动售货机商品掉落声学计数方案:从麦克风到频谱识别的工程实践~YH
人工智能·算法
Mr_liu_6661 小时前
ns3-gym例子解析_基础例子与wifi例子_DQN(3)
开发语言·c++·python·dqn·ns3
土司大王1 小时前
LeetCode hot100——实现 Trie (前缀树)
java·算法·leetcode
水龙吟啸1 小时前
华为研发岗AI方向9.9机考题复盘&分析
人工智能·python·算法·华为
小七在进步1 小时前
类和对象(一)
java·数据结构·算法
Y_Bk1 小时前
2026 ICPC EC网络预选赛第一场
算法
CarIise1 小时前
C语言字符串基础:从char数组到双指针反转算法
算法