## DEV Community is a community of 801,489 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

k@k

Posted on

# Repeated Substring Pattern

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "baba"
Output: True
Explanation: It's the substring "ba" twice.

Example 2:

Input: "xyx"
Output: False

Example 3:

Input: "xyzxyzxyzxyz"
Output: True
Explanation: It's the substring "xyz" four times.
My Solution:

JavaScript:

var repeatedSubstringPattern = function(s) {
return s.repeat(2).slice(1,-1).includes(s);
};

Java:

class Solution {
public boolean repeatedSubstringPattern(String s) {
for(int i=s.length()/2;i>=1;i--){
if(s.length()%i == 0){
int j = i;
String sb = s.substring(0,j);
while(s.indexOf(sb,j) == j) j= j+i;
if(j==s.length()) return true;
}
}
return false;
}
}