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;
    }
};
相关推荐
湖南罗泽南15 分钟前
Windows C++ TCP/IP 两台电脑上互相传输字符串数据
c++·windows·tcp/ip
手握风云-34 分钟前
零基础Java第十六期:抽象类接口(二)
数据结构·算法
可均可可1 小时前
C++之OpenCV入门到提高005:005 图像操作
c++·图像处理·opencv·图像操作
zyx没烦恼1 小时前
【STL】set,multiset,map,multimap的介绍以及使用
开发语言·c++
机器视觉知识推荐、就业指导1 小时前
基于Qt/C++与OpenCV库 实现基于海康相机的图像采集和显示系统(工程源码可联系博主索要)
c++·qt·opencv
笨小古1 小时前
路径规划——RRT-Connect算法
算法·路径规划·导航
<但凡.1 小时前
编程之路,从0开始:知识补充篇
c语言·数据结构·算法
f狐0狸x2 小时前
【数据结构副本篇】顺序表 链表OJ
c语言·数据结构·算法·链表
myloveasuka2 小时前
类与对象(1)
开发语言·c++
paopaokaka_luck2 小时前
基于Spring Boot+Vue的多媒体素材管理系统的设计与实现
java·数据库·vue.js·spring boot·后端·算法