LeetCode 题解工作台

最大重复子字符串

给你一个字符串 sequence ,如果字符串 word 连续重复 k 次形成的字符串是 sequence 的一个子字符串,那么单词 word 的 重复值为 k 。单词 word 的 最 大重复值 是单词 word 在 sequence 中最大的重复值。如果 word 不是 sequence 的子串…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 状态·转移·动态规划

bolt

答案摘要

注意到字符串长度不超过 ,我们直接从大到小枚举 `word` 的重复次数 ,判断 `word` 重复该次数后是否是 `sequence` 的子串,是则直接返回当前的重复次数 。 时间复杂度为 ,其中 为 `sequence` 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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 <= 100
  • 1 <= word.length <= 100
  • sequence 和 word 都只包含小写英文字母。
lightbulb

解题思路

方法一:直接枚举

注意到字符串长度不超过 100100,我们直接从大到小枚举 word 的重复次数 kk,判断 word 重复该次数后是否是 sequence 的子串,是则直接返回当前的重复次数 kk

时间复杂度为 O(n2)O(n^2),其中 nnsequence 的长度。

1
2
3
4
5
6
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
speed

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

最大重复子字符串题解:状态·转移·动态规划 | LeetCode #1668 简单