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' <= s[i] <= '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;
    }
};
相关推荐
Aaron158817 分钟前
RFSOC+VU13P+RK3588的核心优势与应用场景分析
嵌入式硬件·算法·matlab·fpga开发·信息与通信·信号处理·基带工程
优家数科33 分钟前
精准预测:基于多维用水量的滤芯寿命预警算法
算法
脱氧核糖核酸__38 分钟前
LeetCode热题100——189.轮转数组(题解+答案+要点)
数据结构·c++·算法·leetcode
贾斯汀玛尔斯1 小时前
每天学一个算法-快速排序(Quick Sort)
数据结构·算法
炽烈小老头1 小时前
【每天学习一点算法 2026/04/16】逆波兰表达式求值
学习·算法
优家数科1 小时前
水质监测不准?解密云端 TDS 数据建模纠偏算法
算法
木井巳1 小时前
【递归算法】组合总和
java·算法·leetcode·决策树·深度优先·剪枝
coding者在努力1 小时前
被n整除的n位数
c++·算法
赵药师2 小时前
Win11下的VS2022 配置RGBD435i 相机
c++·vs2022·windows11·rgbd435i
量子炒饭大师2 小时前
【C++ 进阶】Cyber霓虹掩体下的代码拟态——【面向对象编程 之 多态】一文带你搞懂C++面向对象编程中的三要素之一————多态!
开发语言·c++·多态