Skip to content

Repeated Substring Pattern

Posted in Education, and WhoCodeFirst

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:

var repeatedSubstringPattern = function(s) {
     return s.repeat(2).slice(1,-1).includes(s);
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;

Happy Coding! 😇

Translate »