LeetCode 题解工作台
哪种连续子字符串更长
给你一个二进制字符串 s 。如果字符串中由 1 组成的 最长 连续子字符串 严格长于 由 0 组成的 最长 连续子字符串,返回 true ;否则,返回 false 。 例如, s = " 11 01 000 10" 中,由 1 组成的最长连续子字符串的长度是 2 ,由 0 组成的最长连续子字符串的长…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们设计一个函数 ,表示字符串 中由 组成的最长连续子字符串的长度。如果 $f(1) \gt f(0)$,那么返回 `true`,否则返回 `false`。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个二进制字符串 s 。如果字符串中由 1 组成的 最长 连续子字符串 严格长于 由 0 组成的 最长 连续子字符串,返回 true ;否则,返回 false 。
- 例如,
s = "110100010"中,由1组成的最长连续子字符串的长度是2,由0组成的最长连续子字符串的长度是3。
注意,如果字符串中不存在 0 ,此时认为由 0 组成的最长连续子字符串的长度是 0 。字符串中不存在 1 的情况也适用此规则。
示例 1:
输入:s = "1101" 输出:true 解释: 由1组成的最长连续子字符串的长度是 2:"1101" 由0组成的最长连续子字符串的长度是 1:"1101" 由 1 组成的子字符串更长,故返回 true 。
示例 2:
输入:s = "111000" 输出:false 解释: 由1组成的最长连续子字符串的长度是 3:"111000" 由0组成的最长连续子字符串的长度是 3:"111000" 由 1 组成的子字符串不比由 0 组成的子字符串长,故返回 false 。
示例 3:
输入:s = "110100010" 输出:false 解释: 由1组成的最长连续子字符串的长度是 2:"110100010" 由0组成的最长连续子字符串的长度是 3:"110100010" 由 1 组成的子字符串不比由 0 组成的子字符串长,故返回 false 。
提示:
1 <= s.length <= 100s[i]不是'0'就是'1'
解题思路
方法一:两次遍历
我们设计一个函数 ,表示字符串 中由 组成的最长连续子字符串的长度。如果 ,那么返回 true,否则返回 false。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
class Solution:
def checkZeroOnes(self, s: str) -> bool:
def f(x: str) -> int:
cnt = mx = 0
for c in s:
if c == x:
cnt += 1
mx = max(mx, cnt)
else:
cnt = 0
return mx
return f("1") > f("0")
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate optimizes the loop to avoid unnecessary comparisons.
- question_mark
Evaluate whether the candidate handles edge cases efficiently.
- question_mark
Look for clear and correct logic when comparing the segment lengths.
常见陷阱
外企场景- error
Failing to handle the case where the string has no 0s or 1s.
- error
Not correctly identifying the longest contiguous segments of 1s and 0s.
- error
Overcomplicating the approach when a simple linear pass would suffice.
进阶变体
外企场景- arrow_right_alt
Consider an approach where the string is processed only once to track segment lengths.
- arrow_right_alt
Implement a solution using dynamic programming if multiple substrings must be compared.
- arrow_right_alt
Adapt the solution for binary data in large files where the string cannot fit entirely into memory.