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;
    }
};
相关推荐
oioihoii3 分钟前
C++11 尾随返回类型:从入门到精通
java·开发语言·c++
叶子2024224 分钟前
守护进程实验——autoDL
人工智能·算法·机器学习
半桔33 分钟前
【算法深练】分组循环:“分”出条理,化繁为简
数据结构·c++·算法·leetcode·面试·职场和发展
天天爱吃肉821833 分钟前
【十年技术演进深度解构:车载充电机(OBC)将成为新能源汽车的“能源大脑”】
python·嵌入式硬件·算法·汽车·能源
KerwinChou_CN1 小时前
自由开发者计划 004:创建一个苹果手机长截屏小程序
图像处理·算法·智能手机·小程序
序属秋秋秋1 小时前
《C++初阶之类和对象》【命名空间 + 输入&输出 + 缺省参数 + 函数重载】
开发语言·c++·笔记
Kethy__1 小时前
算法分析与设计-动态规划、贪心算法
c++·学习·算法·贪心算法·动态规划
闪电麦坤951 小时前
数据结构:递归:泰勒展开式(Taylor Series Expansion)
数据结构·算法
Code_流苏3 小时前
C++课设:学生成绩管理系统
c++·大作业·学生成绩管理系统·c++课设·期末课设
Humbunklung8 小时前
Rust 控制流
开发语言·算法·rust