LeetCode 题解工作台
重复的子字符串
给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。 示例 1: 输入: s = "abab" 输出: true 解释: 可由子串 "ab" 重复两次构成。 示例 2: 输入: s = "aba" 输出: false 示例 3: 输入: s = "abcabcabcabc" 输出…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · string·结合·string·matching
答案摘要
若长度为 的字符串 由 个重复子串组成,将 拼接在自身上,得到字符串 ,长度为 ,此时若从下标 开始查找 ,那么查找到的下标一定小于 的长度。 若长度为 的字符串 不由重复子串组成,将 拼接在自身上,得到字符串 ,长度为 ,此时若从下标 开始查找 ,那么查找到的下标一定等于 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·string·matching 题型思路
题目描述
给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。
示例 1:
输入: s = "abab" 输出: true 解释: 可由子串 "ab" 重复两次构成。
示例 2:
输入: s = "aba" 输出: false
示例 3:
输入: s = "abcabcabcabc" 输出: true 解释: 可由子串 "abc" 重复四次构成。 (或子串 "abcabc" 重复两次构成。)
提示:
1 <= s.length <= 104s由小写英文字母组成
解题思路
方法一:双倍字符串
若长度为 的字符串 由 个重复子串组成,将 拼接在自身上,得到字符串 ,长度为 ,此时若从下标 开始查找 ,那么查找到的下标一定小于 的长度。
若长度为 的字符串 不由重复子串组成,将 拼接在自身上,得到字符串 ,长度为 ,此时若从下标 开始查找 ,那么查找到的下标一定等于 的长度。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
return (s + s).index(s, 1) < len(s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate is able to identify the pattern and suggest multiple methods for solving it.
- question_mark
The candidate considers both the time and space complexity in their solution approach.
- question_mark
The candidate explains string manipulation techniques clearly and concisely.
常见陷阱
外企场景- error
The candidate might suggest overly complicated solutions when a simpler method, such as string concatenation, suffices.
- error
Failing to account for edge cases like non-repeating strings or very short strings.
- error
Overlooking the time complexity of the solution, especially when using nested loops or unnecessary operations.
进阶变体
外企场景- arrow_right_alt
Check if a string can be constructed from a substring with a limited number of repetitions.
- arrow_right_alt
Determine the longest repeating substring that can form a string when repeated.
- arrow_right_alt
Extend the problem to multiple substrings and check if they can collectively form the given string.