LeetCode 题解工作台
找出长度为 K 的特殊子字符串
给你一个字符串 s 和一个整数 k 。 判断是否存在一个长度 恰好 为 k 的子字符串,该子字符串需要满足以下条件: 该子字符串 只包含一个唯一字符 (例如, "aaa" 或 "bbb" )。 如果该子字符串的 前面 有字符,则该字符必须与子字符串中的字符不同。 如果该子字符串的 后面 有字符,则该…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
题目相当于要我们找出每一段连续的相同字符,然后判断是否存在一段长度为 的子字符串,若存在则返回 ,否则返回 。 我们可以用双指针 和 来遍历字符串 ,当 $s[l] = s[r]$ 时, 向右移动,直到 $s[r] \neq s[l]$,此时判断 $r - l$ 是否等于 ,若等于则返回 ,否则 移动到 继续遍历。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个字符串 s 和一个整数 k。
判断是否存在一个长度 恰好 为 k 的子字符串,该子字符串需要满足以下条件:
- 该子字符串 只包含一个唯一字符(例如,
"aaa"或"bbb")。 - 如果该子字符串的 前面 有字符,则该字符必须与子字符串中的字符不同。
- 如果该子字符串的 后面 有字符,则该字符也必须与子字符串中的字符不同。
如果存在这样的子串,返回 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 <= 100s仅由小写英文字母组成。
解题思路
方法一:双指针
题目相当于要我们找出每一段连续的相同字符,然后判断是否存在一段长度为 的子字符串,若存在则返回 ,否则返回 。
我们可以用双指针 和 来遍历字符串 ,当 时, 向右移动,直到 ,此时判断 是否等于 ,若等于则返回 ,否则 移动到 继续遍历。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.