LeetCode 题解工作台
最大重复子字符串
给你一个字符串 sequence ,如果字符串 word 连续重复 k 次形成的字符串是 sequence 的一个子字符串,那么单词 word 的 重复值为 k 。单词 word 的 最 大重复值 是单词 word 在 sequence 中最大的重复值。如果 word 不是 sequence 的子串…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 状态·转移·动态规划
答案摘要
注意到字符串长度不超过 ,我们直接从大到小枚举 `word` 的重复次数 ,判断 `word` 重复该次数后是否是 `sequence` 的子串,是则直接返回当前的重复次数 。 时间复杂度为 ,其中 为 `sequence` 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个字符串 sequence ,如果字符串 word 连续重复 k 次形成的字符串是 sequence 的一个子字符串,那么单词 word 的 重复值为 k 。单词 word 的 最大重复值 是单词 word 在 sequence 中最大的重复值。如果 word 不是 sequence 的子串,那么重复值 k 为 0 。
给你一个字符串 sequence 和 word ,请你返回 最大重复值 k 。
示例 1:
输入:sequence = "ababc", word = "ab" 输出:2 解释:"abab" 是 "ababc" 的子字符串。
示例 2:
输入:sequence = "ababc", word = "ba" 输出:1 解释:"ba" 是 "ababc" 的子字符串,但 "baba" 不是 "ababc" 的子字符串。
示例 3:
输入:sequence = "ababc", word = "ac" 输出:0 解释:"ac" 不是 "ababc" 的子字符串。
提示:
1 <= sequence.length <= 1001 <= word.length <= 100sequence和word都只包含小写英文字母。
解题思路
方法一:直接枚举
注意到字符串长度不超过 ,我们直接从大到小枚举 word 的重复次数 ,判断 word 重复该次数后是否是 sequence 的子串,是则直接返回当前的重复次数 。
时间复杂度为 ,其中 为 sequence 的长度。
class Solution:
def maxRepeating(self, sequence: str, word: str) -> int:
for k in range(len(sequence) // len(word), -1, -1):
if word * k in sequence:
return k
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understanding dynamic programming principles, especially state transitions.
- question_mark
Ability to recognize the need for optimization when brute force becomes inefficient.
- question_mark
Knowledge of string matching techniques like sliding windows and substring searches.
常见陷阱
外企场景- error
Overlooking edge cases where the word doesn't appear in the sequence at all.
- error
Not optimizing the solution when brute force becomes too slow for larger inputs.
- error
Misunderstanding how to track repeated substrings efficiently using dynamic programming.
进阶变体
外企场景- arrow_right_alt
Consider the case where the sequence contains multiple different words and you need to find the maximum k-repeating value for each.
- arrow_right_alt
Explore optimizing the space complexity of the dynamic programming approach for even larger inputs.
- arrow_right_alt
Extend the problem to allow the word to repeat non-consecutively and calculate the number of total occurrences.