我们需要编写一个将字符串作为唯一参数的JavaScript函数。我们的函数需要检查是否可以通过获取字符串str的子字符串并将该子字符串的多个副本附加在一起来构造字符串str。
例如,如果函数的输入为-
const str = 'thisthisthisthis';
那么输出应该是-
const output = true;
因为该字符串是通过反复附加“ this”字符串而制成的。
为此的代码将是-
const str = 'thisthisthisthis';
const repeatedSubstring = (str = '') => {
const {length} = str;
const checkSubString = ss => {
const m = ss.length;
for (let i = 0; i < length; i += m)
for (let j = 0; j < m; j++)
if (str[i+j] !== ss[j])
return false;
return true;
};
let factor = 2, len;
while (length/factor >= 1){
while (length % factor) factor++;
len = length/factor;
if (checkSubString(str.substring(0,len))){
return true;
};
factor++;
};
return false;
};
console.log(repeatedSubstring(str));首先,我们设置子字符串模式检查功能。
然后,我们遍历所有可能的因素,均匀地分割字符串str,以确定是否找到了可行的重复模式。
输出结果
控制台中的输出将是-
true