如果字符串 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
热门推荐
10 寒露祝福语毕业寄语简短
11 虎年文案简短祝福语长辈
12 文学短句祝福语大全简短
13 郑伊健结婚祝福语简短高级
14 银行考研上岸祝福语简短
15 硕士毕业蛋糕祝福语简短
16 对航母的祝福语简短
17 离职横幅升职祝福语简短
18 宝宝祝福语简短刻字文案