LeetCode 题解工作台

找出长度为 K 的特殊子字符串

给你一个字符串 s 和一个整数 k 。 判断是否存在一个长度 恰好 为 k 的子字符串,该子字符串需要满足以下条件: 该子字符串 只包含一个唯一字符 (例如, "aaa" 或 "bbb" )。 如果该子字符串的 前面 有字符,则该字符必须与子字符串中的字符不同。 如果该子字符串的 后面 有字符,则该…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

题目相当于要我们找出每一段连续的相同字符,然后判断是否存在一段长度为 的子字符串,若存在则返回 ,否则返回 。 我们可以用双指针 和 来遍历字符串 ,当 $s[l] = s[r]$ 时, 向右移动,直到 $s[r] \neq s[l]$,此时判断 $r - l$ 是否等于 ,若等于则返回 ,否则 移动到 继续遍历。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s 和一个整数 k

判断是否存在一个长度 恰好 k 的子字符串,该子字符串需要满足以下条件:

  1. 该子字符串 只包含一个唯一字符(例如,"aaa""bbb")。
  2. 如果该子字符串的 前面 有字符,则该字符必须与子字符串中的字符不同。
  3. 如果该子字符串的 后面 有字符,则该字符也必须与子字符串中的字符不同。

如果存在这样的子串,返回 true;否则,返回 false

子字符串 是字符串中的连续、非空字符序列。

 

示例 1:

输入: s = "aaabaaa", k = 3

输出: true

解释:

子字符串 s[4..6] == "aaa" 满足条件:

  • 长度为 3。
  • 所有字符相同。
  • 子串 "aaa" 前的字符是 'b',与 'a' 不同。
  • 子串 "aaa" 后没有字符。

示例 2:

输入: s = "abc", k = 2

输出: false

解释:

不存在长度为 2 、仅由一个唯一字符组成且满足所有条件的子字符串。

 

提示:

  • 1 <= k <= s.length <= 100
  • s 仅由小写英文字母组成。
lightbulb

解题思路

方法一:双指针

题目相当于要我们找出每一段连续的相同字符,然后判断是否存在一段长度为 kk 的子字符串,若存在则返回 true\textit{true},否则返回 false\textit{false}

我们可以用双指针 llrr 来遍历字符串 ss,当 s[l]=s[r]s[l] = s[r] 时,rr 向右移动,直到 s[r]s[l]s[r] \neq s[l],此时判断 rlr - l 是否等于 kk,若等于则返回 true\textit{true},否则 ll 移动到 rr 继续遍历。

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

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def hasSpecialSubstring(self, s: str, k: int) -> bool:
        l, n = 0, len(s)
        while l < n:
            r = l
            while r < n and s[r] == s[l]:
                r += 1
            if r - l == k:
                return True
            l = r
        return False
speed

复杂度分析

指标
时间complexity is O(n) because each character is visited once. Space complexity is O(1) since only counters and current character tracking are used.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Emphasizes whether you recognize the string-driven pattern for consecutive identical characters.

  • question_mark

    Checks if you can optimize by early exit when substring length cannot be satisfied.

  • question_mark

    Wants clear O(n) traversal without extra data structures.

warning

常见陷阱

外企场景
  • error

    Counting non-consecutive identical characters incorrectly across gaps.

  • error

    Not handling edge cases where k equals string length or 1.

  • error

    Forgetting to reset the consecutive counter when characters change.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check for substrings with exactly two distinct characters repeating alternately.

  • arrow_right_alt

    Find the longest substring of consecutive identical characters instead of fixed length k.

  • arrow_right_alt

    Return all starting indices of valid substrings rather than a boolean result.

help

常见问题

外企场景

找出长度为 K 的特殊子字符串题解:String-driven solution … | LeetCode #3456 简单