LeetCode 459. Repeated Substring Pattern
Given a string
s
, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
I encountered this question in a mock interview, just playing around since my friends and I are bored, and somehow got a TLE for this supposedly easy level question!!! How could that even happen?
My first approach to this question is to simply use a recursive method and try and find any possible repeating substrings. The code is as the following:
class Solution {
// recursive function to check whether a string starts with the given pattern
bool check(string s, int start, string pattern){
// check the prefix of the string against the pattern
if(s.substr(start, pattern.length()) == pattern){
// pass the string with the prefix ignored
return check(s, start+pattern.length(), pattern);
}
return start != s.length() ? false : true;
}
public:
bool repeatedSubstringPattern(string s) {
// generate the first possible substring
string pattern = s.substr(0, 1);
// try out all possible substrings
for(int i = 1; i <= s.length() / 2; i++){
if(check(s, pattern.length(), pattern))
return true;
pattern += s[i];
}
return false;
}
};
And then, I came across this ingenious solution in discussion:
class Solution {
public:
bool repeatedSubstringPattern(string s) {
return (s + s).substr(1, 2 * s.length() - 2).find(s) != -1;
}
};
What in the world is that???
This simple one-line solution has my jaw dropped to the core of Earth. I tried to understand the magic and here is me trying to explain why it works:
Let us take an example of "AAAA", where 'A' stands for any repeated substring.
We will first double the entire string, resulting in "AAAAAAAA", and then remove the first and last character in this string: "bAAAAAAc", where b and c stand for the substring with its first and last element removed. Since the given string is generated by repeating a substring, we are expected to find one in our new string. Even if the entire string is somehow "rotate", meaning the head might now be in the middle, the resulting string should still contain a copy of the original as the "rotation" does not alter how the characters line out.
Let us repeat the same experiment with a counter-example, say "ABCDEFG", where each character in the string represents any distinct substring.
When we double the entire string, it becomes: "ABCDEFGABCDEFG", and after removing the head and tail, we have: "xBCDEFGABCDEFy", where x and y represent the two shortened substrings. We can see that the original string, "ABCDEFG", no longer appears in the same order, thus telling us that it is not made by repeating any single substring.
I truly admire the one who comes with this method. How big-brain is he? XP