LeetCode 题解工作台
计数二进制子串
给定一个字符串 s ,统计并返回具有相同数量 0 和 1 的非空(连续)子字符串的数量,并且这些子字符串中的所有 0 和所有 1 都是成组连续的。 重复出现(不同位置)的子串也要统计它们出现的次数。 示例 1: 输入: s = "00110011" 输出: 6 解释: 6 个子串满足具有相同数量的连…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们可以遍历字符串 ,用一个变量 记录上一个连续字符的数量,另一个变量 记录当前连续字符的数量。那么以当前字符结尾的满足条件的子串数量为 $\min(\textit{pre}, \textit{cur})$。我们将 $\min(\textit{pre}, \textit{cur})$ 累加到答案中,并将 的值赋给 ,继续遍历字符串 直到结束。 时间复杂度 ,其中 是字符串 的长度。空间…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个字符串 s,统计并返回具有相同数量 0 和 1 的非空(连续)子字符串的数量,并且这些子字符串中的所有 0 和所有 1 都是成组连续的。
重复出现(不同位置)的子串也要统计它们出现的次数。
示例 1:
输入:s = "00110011" 输出:6 解释:6 个子串满足具有相同数量的连续 1 和 0 :"0011"、"01"、"1100"、"10"、"0011" 和 "01" 。 注意,一些重复出现的子串(不同位置)要统计它们出现的次数。 另外,"00110011" 不是有效的子串,因为所有的 0(还有 1 )没有组合在一起。
示例 2:
输入:s = "10101" 输出:4 解释:有 4 个子串:"10"、"01"、"10"、"01" ,具有相同数量的连续 1 和 0 。
提示:
1 <= s.length <= 105s[i]为'0'或'1'
解题思路
方法一:遍历计数
我们可以遍历字符串 ,用一个变量 记录上一个连续字符的数量,另一个变量 记录当前连续字符的数量。那么以当前字符结尾的满足条件的子串数量为 。我们将 累加到答案中,并将 的值赋给 ,继续遍历字符串 直到结束。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
class Solution:
def countBinarySubstrings(self, s: str) -> int:
n = len(s)
ans = i = 0
pre = 0
while i < n:
j = i + 1
while j < n and s[j] == s[i]:
j += 1
cur = j - i
ans += min(pre, cur)
pre = cur
i = j
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Look for an understanding of how to manage multiple groups of consecutive 1's and 0's efficiently.
- question_mark
Evaluate if the candidate can explain the trade-offs between time complexity and space optimization in this problem.
- question_mark
Check for the ability to reason about how to handle substrings that repeat in the final count.
常见陷阱
外企场景- error
Failing to handle repeated substrings correctly – the solution should count each occurrence of valid substrings.
- error
Incorrectly grouping consecutive characters, which may lead to missing valid substrings.
- error
Not optimizing space by avoiding unnecessary data structures – the two-pointer approach should be used with careful tracking.
进阶变体
外企场景- arrow_right_alt
Consider if the input string includes alternating characters, like "010101".
- arrow_right_alt
What happens if the binary string has segments where the count of 0's or 1's exceeds the count of the other?
- arrow_right_alt
How would the solution adapt if we are asked to find the longest valid substring instead of counting them?