LeetCode 题解工作台

检查二进制字符串字段

给你一个二进制字符串 s ,该字符串 不含前导零 。 如果 s 包含 零个或一个由连续的 '1' 组成的字段 ,返回 true ​​​ 。否则,返回 false 。 示例 1: 输入: s = "1001" 输出: false 解释: 由连续若干个 '1' 组成的字段数量为 2,返回 false 示…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

注意到字符串 不含前导零,说明 以 '1' 开头。 若字符串 存在 "01" 串,那么 就是形如 "1...01..." 的字符串,此时 出现了至少两个连续的 '1' 片段,不满足题意,返回 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二进制字符串 s ,该字符串 不含前导零

如果 s 包含 零个或一个由连续的 '1' 组成的字段 ,返回 true​​​ 。否则,返回 false

 

示例 1:

输入:s = "1001"
输出:false
解释:由连续若干个 '1' 组成的字段数量为 2,返回 false

示例 2:

输入:s = "110"
输出:true

 

提示:

  • 1 <= s.length <= 100
  • s[i]​​​​ 为 '0''1'
  • s[0]'1'
lightbulb

解题思路

方法一:脑筋急转弯

注意到字符串 ss 不含前导零,说明 ss 以 '1' 开头。

若字符串 ss 存在 "01" 串,那么 ss 就是形如 "1...01..." 的字符串,此时 ss 出现了至少两个连续的 '1' 片段,不满足题意,返回 false\textit{false}

若字符串 ss 不存在 "01" 串,那么 ss 只能是形如 "1..1000..." 的字符串,此时 ss 只有一个连续的 '1' 片段,满足题意,返回 true\textit{true}

因此,只需要判断字符串 ss 是否存在 "01" 串即可。

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

1
2
3
4
class Solution:
    def checkOnesSegment(self, s: str) -> bool:
        return '01' not in s
speed

复杂度分析

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

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

检查二进制字符串字段题解:String-driven solution … | LeetCode #1784 简单