如果字符串 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 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练