字符串是JavaScript中重复的子字符串的组合吗
问题
我们需要编写一个将字符串作为唯一参数的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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下