ปัญหา
รับสตริง str ตรวจสอบว่าเป็นการซ้ำของ substring ย่อยๆ หรือไม่
ตัวอย่าง
const str = 'thisthisthisthis';
ซ้ำของ "this" → true
โค้ดตัวอย่าง
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));
คำอธิบาย
ตรวจสอบตัวประกอบของความยาวสตริง ลอง substring ความยาว length/factor ว่าซ้ำได้หมดหรือไม่
ผลลัพธ์
true