例如:
function scramble(str1, str2) {
for (var i = 0; i < str2.length; i++) {
var letter = str1.indexOf(str2[i]);
if (letter !== -1) {
str1 = str1.substring(0, letter) + str1.substring(letter + 1);
} else {
return false;
}
}
return true;
}
scramble('rkqodlw', 'world') ==> True
但是仍然很慢。我该如何修改此功能?
答案 0 :(得分:1)
您可以对字符串的字符进行排序,并查找所需字符串的字符。
function scramble(left, right) {
const a = [...left].sort();
var i = 0;
return [...right]
.sort()
.every(c => i = a.indexOf(c, i) + 1);
}
console.log(scramble('rkqodlw', 'world'));
console.log(scramble('rkqodlw', 'foo'));