LeetCode 题解工作台
检查二进制字符串字段
给你一个二进制字符串 s ,该字符串 不含前导零 。 如果 s 包含 零个或一个由连续的 '1' 组成的字段 ,返回 true 。否则,返回 false 。 示例 1: 输入: s = "1001" 输出: false 解释: 由连续若干个 '1' 组成的字段数量为 2,返回 false 示…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
注意到字符串 不含前导零,说明 以 '1' 开头。 若字符串 存在 "01" 串,那么 就是形如 "1...01..." 的字符串,此时 出现了至少两个连续的 '1' 片段,不满足题意,返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个二进制字符串 s ,该字符串 不含前导零 。
如果 s 包含 零个或一个由连续的 '1' 组成的字段 ,返回 true 。否则,返回 false 。
示例 1:
输入:s = "1001"
输出:false
解释:由连续若干个 '1' 组成的字段数量为 2,返回 false
示例 2:
输入:s = "110" 输出:true
提示:
1 <= s.length <= 100s[i] 为'0'或'1's[0]为'1'
解题思路
方法一:脑筋急转弯
注意到字符串 不含前导零,说明 以 '1' 开头。
若字符串 存在 "01" 串,那么 就是形如 "1...01..." 的字符串,此时 出现了至少两个连续的 '1' 片段,不满足题意,返回 。
若字符串 不存在 "01" 串,那么 只能是形如 "1..1000..." 的字符串,此时 只有一个连续的 '1' 片段,满足题意,返回 。
因此,只需要判断字符串 是否存在 "01" 串即可。
时间复杂度 。其中 为字符串 的长度。空间复杂度 。
class Solution:
def checkOnesSegment(self, s: str) -> bool:
return '01' not in s
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focus on counting segments of '1's efficiently.
- question_mark
Ensure the approach handles edge cases like all '1's or '0's.
- question_mark
Evaluate whether a more optimized solution can reduce redundant checks.
常见陷阱
外企场景- error
Miscounting the segments due to improper string scanning.
- error
Not handling edge cases like strings with no '1's or strings where all characters are '1'.
- error
Overcomplicating the solution by introducing unnecessary data structures.
进阶变体
外企场景- arrow_right_alt
What if the string has leading or trailing zeros? The logic can be adapted to handle these cases effectively.
- arrow_right_alt
How would the solution change if we allowed the string to contain other characters? This introduces complexity in the segmentation logic.
- arrow_right_alt
Can we optimize further for strings with very large lengths? Explore constant space solutions.