字串是否是 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
廣告