LeetCode 题解工作台

最长平衡子字符串

给你一个仅由 0 和 1 组成的二进制字符串 s 。 如果子字符串中 所有的 0 都在 1 之前 且其中 0 的数量等于 1 的数量,则认为 s 的这个子字符串是平衡子字符串。请注意,空子字符串也视作平衡子字符串。 返回 s 中最长的平衡子字符串长度。 子字符串是字符串中的一个连续字符序列。 示例 …

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

注意到数据范围很小,因此,我们可以枚举所有的子串 ,检查其是否为平衡子串,如果是,则更新答案。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个仅由 01 组成的二进制字符串 s  

如果子字符串中 所有的 0 都在 1 之前 且其中 0 的数量等于 1 的数量,则认为 s 的这个子字符串是平衡子字符串。请注意,空子字符串也视作平衡子字符串。 

返回  s 中最长的平衡子字符串长度。

子字符串是字符串中的一个连续字符序列。

 

示例 1:

输入:s = "01000111"
输出:6
解释:最长的平衡子字符串是 "000111" ,长度为 6 。

示例 2:

输入:s = "00111"
输出:4
解释:最长的平衡子字符串是 "0011" ,长度为  4 。

示例 3:

输入:s = "111"
输出:0
解释:除了空子字符串之外不存在其他平衡子字符串,所以答案为 0 。

 

提示:

  • 1 <= s.length <= 50
  • '0' <= s[i] <= '1'
lightbulb

解题思路

方法一:暴力枚举

注意到数据范围很小,因此,我们可以枚举所有的子串 s[i..j]s[i..j],检查其是否为平衡子串,如果是,则更新答案。

时间复杂度 O(n3)O(n^3),空间复杂度 O(1)O(1)。其中 nn 为字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def findTheLongestBalancedSubstring(self, s: str) -> int:
        def check(i, j):
            cnt = 0
            for k in range(i, j + 1):
                if s[k] == '1':
                    cnt += 1
                elif cnt:
                    return False
            return cnt * 2 == (j - i + 1)

        n = len(s)
        ans = 0
        for i in range(n):
            for j in range(i + 1, n):
                if check(i, j):
                    ans = max(ans, j - i + 1)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate is familiar with string manipulation and optimization strategies.

  • question_mark

    The candidate can implement efficient substring checks with prefix sum or sliding window.

  • question_mark

    The candidate can distinguish between brute force and optimized approaches.

warning

常见陷阱

外企场景
  • error

    Incorrectly counting zeroes and ones in a substring.

  • error

    Overlooking cases where no balanced substring exists.

  • error

    Not considering the empty substring as balanced in the edge cases.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling edge cases with no balanced substrings.

  • arrow_right_alt

    Optimizing with different window sizes.

  • arrow_right_alt

    Applying different balancing rules such as alternating zeroes and ones.

help

常见问题

外企场景

最长平衡子字符串题解:String-driven solution … | LeetCode #2609 简单