JavaScript 中是否可以用一個字串重複生成另一個字串


問題

我們需要編寫一個 JavaScript 函式,它將兩個字串 str1 和 str2 作為第一個和第二個引數。

我們的函式應返回重複字串 str1 的最少次數,以便字串 str2 為其子字串。如果在重複 str2 後不可能成為 a 的子字串,則應返回 -1

例如,如果輸入函式是這樣

輸入

const str1 = 'wxyz';
const str2 = 'yzwxyzwx';

輸出

const output = 3;

輸出解釋

我們返回 3,因為透過將 a 重複三次 "abcdabcdabcd",b 是其子字串。

示例

以下是程式碼 -

 即時演示

const str1 = 'wxyz';
const str2 = 'yzwxyzwx';
const countRepeat = (str1 = '', str2) => {
   let i = 1
   let current = str1
   while (true) {
      if (current.indexOf(str2) >= 0) {
         return i
      }
      if ((current.length > str2.length * 2) && i > 2) {
         return -1
      }
      current += str1
      i += 1
   }
}
console.log(countRepeat(str1, str2));

輸出

3

更新於: 24-04-2021

65 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.