Problem
Given a string s
, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Create Multiple Substring and Checking Till length/2
Here is the approach:
- The length of the repeating substring must be a divisor of the length of the input string.
- Search for all possible divisors of
str.length()
, starting fromlength / 2
. - If
i
is a divisor oflength
, repeat the substring from0
toi
the number of timesi
fits intos.length
. - If the repeated substring equals the input
str
, returntrue
.
For example, for the string s = "abcabcabcabc"
, the half string is abcabc
. Since the first half and the second half are identical, we return true.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
. The outer loop runsO(n/2)
times, and the inner concatenation could runO(n)
in the worst case. - 🧺 Space complexity:
O(n)
. Due to creating substrings and the StringBuilder in Java or equivalent operations in Python.