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;
    }
};
相关推荐
SimpleLearingAI8 分钟前
聚类算法详解
算法·数据挖掘·聚类
刀法如飞1 小时前
Go 字符串查找的 20 种实现方式,用不同思路解决问题
算法·面试·程序员
Byron Loong2 小时前
【c++】为什么有了dll和.h,还需要包含lib
java·开发语言·c++
Dlrb12113 小时前
C语言-指针数组与数组指针
c语言·数据结构·算法·指针·数组指针·指针数组·二级指针
WL_Aurora3 小时前
Python 算法基础篇之集合
python·算法
坚果派·白晓明3 小时前
【鸿蒙PC三方库移植适配框架解读系列】第一篇:Lycium C/C++ 三方库适配 — 概述与环境配置
c语言·开发语言·c++·harmonyos·开源鸿蒙·三方库·c/c++三方库
平行侠3 小时前
A15 工业路由器IP前缀高速检索与内存压缩系统
网络·tcp/ip·算法
咩咦4 小时前
C++学习笔记02:cin 和 cout 输入输出
c++·学习笔记·cin·输入输出·cout
咩咦4 小时前
C++学习笔记05:引用和常引用
c++·学习笔记·引用·const·常引用
香蕉鼠片4 小时前
算法过程中不会的
开发语言·c++