How do I check if a string is entirely made of the same substring?

I have to create a function which takes a string, and it should return true or false based on whether the input consists of a repeated character sequence. The length of given string is always greater than 1 and the character sequence must have at least one repetition.

"aa" // true(entirely contains two strings "a")
"aaa" //true(entirely contains three string "a")
"abcabcabc" //true(entirely containas three strings "abc")

“aba” //false(At least there should be two same substrings and nothing more)
“ababa” //false(“ab” exists twice but “a” is extra so false)

I have created a function, but it’s:

function check(str){
if(!(str.length && str.length - 1)) return false;
let temp = ‘’;
for(let i = 0;i<=str.length/2;i++){
temp += str[i]
//console.log(str.replace(new RegExp(temp,“g”),‘’))
if(!str.replace(new RegExp(temp,“g”),‘’)) return true;
}
return false;
}

console.log(check(‘aa’)) //true
console.log(check(‘aaa’)) //true
console.log(check(‘abcabcabc’)) //true
console.log(check(‘aba’)) //false
console.log(check(‘ababa’)) //false

Checking of this is part of the real problem. I can’t afford a non-efficient solution like this. First of all it’s looping through half of the string.

The second problem is that its using replace() in each loop which makes it slow. Is there a better solution regarding performance?

#javascript #string #algorithm

1 Likes3.40 GEEK