如果字符串 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 婆婆高寿祝福语大全简短