字符串是否是 JavaScript 中重复子字符串的组合
问题
要求我们编写一个 JavaScript 函数,该函数以一个字符字符串作为唯一参数。我们的函数需要检查字符串 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP