LeetCode 题解工作台

重复的子字符串

给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。 示例 1: 输入: s = "abab" 输出: true 解释: 可由子串 "ab" 重复两次构成。 示例 2: 输入: s = "aba" 输出: false 示例 3: 输入: s = "abcabcabcabc" 输出…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · string·结合·string·matching

bolt

答案摘要

若长度为 的字符串 由 个重复子串组成,将 拼接在自身上,得到字符串 ,长度为 ,此时若从下标 开始查找 ,那么查找到的下标一定小于 的长度。 若长度为 的字符串 不由重复子串组成,将 拼接在自身上,得到字符串 ,长度为 ,此时若从下标 开始查找 ,那么查找到的下标一定等于 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 string·结合·string·matching 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。

 

示例 1:

输入: s = "abab"
输出: true
解释: 可由子串 "ab" 重复两次构成。

示例 2:

输入: s = "aba"
输出: false

示例 3:

输入: s = "abcabcabcabc"
输出: true
解释: 可由子串 "abc" 重复四次构成。 (或子串 "abcabc" 重复两次构成。)

 

提示:

  • 1 <= s.length <= 104
  • s 由小写英文字母组成
lightbulb

解题思路

方法一:双倍字符串

若长度为 nn 的字符串 ss 由 mm 个重复子串组成,将 ss 拼接在自身上,得到字符串 ssss,长度为 2n2n,此时若从下标 11 开始查找 ss,那么查找到的下标一定小于 ss 的长度。

若长度为 nn 的字符串 ss 不由重复子串组成,将 ss 拼接在自身上,得到字符串 ssss,长度为 2n2n,此时若从下标 11 开始查找 ss,那么查找到的下标一定等于 ss 的长度。

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

1
2
3
4
class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        return (s + s).index(s, 1) < len(s)
speed

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

重复的子字符串题解:string·结合·string·matchi… | LeetCode #459 简单