Repeated Substring Pattern
LeetCode 459 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.
Example 2:
Input: s = "aba"
Output: false
Example 3:
Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times or the substring "abcabc" twice.
Constraints:
- `1 <= s.length <= 10^4`
- `s` consists of lowercase English letters.
Topics: String, String Matching
Approachβ
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
When to use
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 384 ms)β
| Metric | Value |
|---|---|
| Runtime | 384 ms |
| Memory | N/A |
| Date | 2018-04-04 |
Solution
public class Solution {
public bool RepeatedSubstringPattern(string s) {
int n = s.Length;
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n/2; i++)
{
if(n%i!=0) continue;
sb.Clear();
string substr = s.Substring(0,i);
while(sb.Length < n)
{
sb.Append(substr);
}
if(sb.ToString().Equals(s)) return true;
}
return false;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.