有什么方法可以做array.includs忽略顺序吗



如果数组第一个元素中的字符串包含数组第二个元素中字符串的所有字母,那么我想要一个返回true的函数。

例如,["hello","hello"]应该返回true,因为第二个字符串中的所有字母都出现在第一个字符串中,忽略大小写。

参数["hello","hey"]应该返回false,因为字符串hello不包含y.

最后,["Alien","line"]应该返回true,因为行中的所有字母都存在于Alien中。

这是我目前拥有的代码:

function mutation(arr) {
return arr[0].includes(arr[1]);
}

如果我插入像"dinosaur"、"dino"或"coding"、"ding"这样的参数,它将返回true,这是可以的。但是,如果我插入像"dinosaur"、"dnour"或"coding"、"gnidoc"这样的参数,它将返回false,我希望返回true。实现这一点最简单的方法是什么?

执行此测试的最有效方法是将数组的第一个元素转换为Set,然后检查第二个元素中的每个字符是否都在集合中:

function mutation(arr) {
first = new Set(arr[0].toLowerCase())
return [...arr[1].toLowerCase()].every(char => first.has(char))
}
console.log(mutation(['hello', 'Hello']));
console.log(mutation(['hello', 'hey']));
console.log(mutation(['Alien', 'line']));
console.log(mutation(['dinosaur', 'dino']));
console.log(mutation(['dinosaur', 'onion']));
console.log(mutation(['coding', 'ding']));
console.log(mutation(['coding', 'gniDoc']));

(通过规范(保证集合的查找时间少于O(n)(合理的实现将是具有O(1)查找时间的哈希表(,因此这将比使用Array.includes的循环更快。

请注意,此代码假定mutation(['abc', 'aaa'])应该是true,因为字母a确实出现在数组的第一个元素中(只是不出现3次(。

您是其中的一员。理想情况下,您希望对第二个单词中的字符进行迭代,并检查第一个单词中every字符是否为included

注意:要使用every(一种数组方法(,您需要将字符串强制为一个字符数组,您可以使用Array.from或扩展语法([...string](

function check([ first, second ]) {
return [...second.toLowerCase()].every(char => {
return first.toLowerCase().includes(char);
});
}
console.log(check(['hello', 'Hello']));
console.log(check(['hello', 'hey']));
console.log(check(['Alien', 'line']));
console.log(check(['dinosaur', 'dino']));
console.log(check(['dinosaur', 'dnour']));
console.log(check(['coding', 'ding']));
console.log(check(['coding', 'gniDoc']));
console.log(check(['coding', 'fuzzycoding']));

一个解决方案可以有两个嵌套循环,但这会有点慢。

时间复杂度将O(m*n(

第一个元素的大小:m,第二个元素的大小n

这可以通过使用hashMap和通过计数对第一个元素字母进行索引来改进。

当对字母进行计数时,您可以迭代第二个元素,并通过将其与每个字母进行比较来减少计数器。当没有匹配时,它将是假的。

最后,您将拥有O(max(m,n((的时间复杂度,它优于O(m*n(

function mutation([first, second]) {
const idxs = new Map();
for(const f of first) {
const l = f.toLowerCase();
if(!idxs.has(l)) idxs.set(l, 1);
else idxs.set(l, idxs.get(l) + 1);
}

for(const s of second) {
const l = s.toLowerCase();
const val = idxs.get(l);
if(val && val > 0) {
idxs.set(l, idxs.get(l) - 1);
} else {
return false;
}
}

return true;
}
const tests = [
[["hello", "Hello"], true],
[["hello", "hey"], false],
[["Alien", "line"], true],
[['dinosaur', 'dino'], true],
[['dinosaur', 'dnour'], true],
[['coding', 'gnidoc'], true]
];
for(const [parameters, expected] of tests){
const result = mutation(parameters);
console.assert(result === expected, {parameters, expected});
console.log(parameters, result === expected ? 'PASSED': 'FAILED')
}

最新更新