DEV Community

k@k
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;
}
}

Happy Coding! πŸ˜‡ please share your approach on comments...

Image of Wix Studio

2025: Your year to build apps that sell

Dive into hands-on resources and actionable strategies designed to help you build and sell apps on the Wix App Market.

Get started

Top comments (0)

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay