如果字符串 1 的一部分可以重新排列为字符串 2,如何编写返回 true 的 JavaScript 函数?
我们必须编写一个函数,如果string1的一部分可以重新排列为string2,则返回true。编写函数,比如scramble(str1,str2),如果str1字符的一部分可以重新排列以匹配str2,则返回true,否则返回false。
例如-
Let’s say string1 is str1 and string2 is str2. str1 is 'cashwool' and str2 is ‘school’ the output should return true. str1 is 'katas' and str2 is 'steak' should return false.
所以,这是执行此操作的代码。我们简单地对两个字符串进行拆分和排序,然后检查较小的字符串是否是较大字符串的子字符串。
这样做的完整代码将是-
示例
const str1 = 'cashwool';
const str2 = 'school';
const scramble = (str1, str2) => {
const { length: len1 } = str1;
const { length: len2 } = str2;
const firstSortedString = str1.split("").sort().join("");
const secondSortedString = str2.split("").sort().join("");
if(len1 > len2){
return firstSortedString.includes(secondSortedString);
}
return secondSortedString.includes(firstSortedString);
};
console.log(scramble(str1, str2));输出结果控制台中的输出将是-
true
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下