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;
    }
};
相关推荐
kali-Myon14 小时前
NewStarCTF2025-Week2-Pwn
算法·安全·gdb·pwn·ctf·栈溢出
老四啊laosi14 小时前
[双指针] 1. 力扣283.移动零
算法·leetcode·双指针·移动零
每天学一点儿14 小时前
感知机:单层,多层(二分类,多分类)
人工智能·算法
磊灬泽15 小时前
【Linux驱动开发】PWM子系统-servo
linux·运维·算法
wan5555cn15 小时前
当代社会情绪分类及其改善方向深度解析
大数据·人工智能·笔记·深度学习·算法·生活
陈增林16 小时前
基于 PyQt5 的多算法视频关键帧提取工具
开发语言·qt·算法
郝学胜-神的一滴16 小时前
Linux系统函数stat和lstat详解
linux·运维·服务器·开发语言·c++·程序人生·软件工程
owCode17 小时前
3-C++中类大小影响因素
开发语言·c++
C嘎嘎嵌入式开发17 小时前
【机器学习算法篇】K-近邻算法
算法·机器学习·近邻算法