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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP