Skip to content

459. Repeated Substring Pattern

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 <= 104
  • s consists of lowercase English letters.

Solutions

Solution 1

Thinking

We ask whether \(s\) is a proper prefix repeated. Trying every prefix length is \(O(n^2)\).

Build \(s+s\) and search for \(s\) starting at index \(1\). A hit before \(n\) means \(s\) lines up inside the concatenation, hence a period exists.

Starting at \(1\) skips the trivial match at \(0\); a hit at \(n\) is only the middle copy, so there is no smaller period.

1
2
3
class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        return (s + s).index(s, 1) < len(s)
1
2
3
4
5
6
class Solution {
    public boolean repeatedSubstringPattern(String s) {
        String str = s + s;
        return str.substring(1, str.length() - 1).contains(s);
    }
}
1
2
3
4
5
6
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        return (s + s).find(s, 1) < s.size();
    }
};
1
2
3
func repeatedSubstringPattern(s string) bool {
    return strings.Index(s[1:]+s, s) < len(s)-1
}
1
2
3
function repeatedSubstringPattern(s: string): boolean {
    return (s + s).slice(1, (s.length << 1) - 1).includes(s);
}
1
2
3
4
5
impl Solution {
    pub fn repeated_substring_pattern(s: String) -> bool {
        (s.clone() + &s)[1..s.len() * 2 - 1].contains(&s)
    }
}

Comments