如果字符串 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 生日广州男生祝福语简短