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;
    }
};
相关推荐
咩咦3 小时前
C++学习笔记28:静态成员应用:不用循环求1到n的和
c++·学习笔记·类和对象·static·构造函数·oj·静态成员
EllinY3 小时前
CF2217E Definitely Larger 题解
c++·笔记·算法·构造
筠筠喵呜喵4 小时前
Linux软件开发性能优化
linux·c++·性能优化
Bruce_kaizy4 小时前
c++ linux环境编程——文件io介绍以及open 、write 、read 三剑客深度详解
linux·服务器·c++·ubuntu·操作系统·文件io
PAK向日葵6 小时前
我用 C++ 写了一个轻量级 Python 虚拟机,刚刚开源
c++·python·开源
玖釉-6 小时前
下一个排列:从字典序到原地算法的完整推导
数据结构·c++·windows·算法
IronMurphy6 小时前
【算法五十】62. 不同路径
算法
影寂ldy6 小时前
C#一维数组
算法
枕星而眠7 小时前
数据结构八大排序详解(一):四大简单排序
c语言·数据结构·c++·后端