LeetCode 题解工作台

哪种连续子字符串更长

给你一个二进制字符串 s 。如果字符串中由 1 组成的 最长 连续子字符串 严格长于 由 0 组成的 最长 连续子字符串,返回 true ;否则,返回 false 。 例如, s = " 11 01 000 10" 中,由 1 组成的最长连续子字符串的长度是 2 ,由 0 组成的最长连续子字符串的长…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们设计一个函数 ,表示字符串 中由 组成的最长连续子字符串的长度。如果 $f(1) \gt f(0)$,那么返回 `true`,否则返回 `false`。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二进制字符串 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 <= 100
  • s[i] 不是 '0' 就是 '1'
lightbulb

解题思路

方法一:两次遍历

我们设计一个函数 f(x)f(x),表示字符串 ss 中由 xx 组成的最长连续子字符串的长度。如果 f(1)>f(0)f(1) \gt f(0),那么返回 true,否则返回 false

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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")
speed

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

哪种连续子字符串更长题解:String-driven solution … | LeetCode #1869 简单