最大单词长度乘积
给你一个字符串数组 words ,找出并返回 length(words[i]) * length(words[j]) 的最大值,并且这两个单词不含有公共字母。如果不存在这样的两个单词,返回 0 。
示例 1:
输入:words = ["abcw","baz","foo","bar","xtfn","abcdef"]
输出:16
解释:这两个单词为 "abcw", "xtfn"。
1
2
3
2
3
var maxProduct = function(words) {
const length = words.length;
const masks = new Array(length).fill(0);
for (let i = 0; i < length; i++) {
const word = words[i];
const wordLength = word.length;
for (let j = 0; j < wordLength; j++) {
masks[i] |= 1 << (word[j].charCodeAt() - 'a'.charCodeAt());
}
}
let maxProd = 0;
for (let i = 0; i < length; i++) {
for (let j = i + 1; j < length; j++) {
if ((masks[i] & masks[j]) === 0) {
maxProd = Math.max(maxProd, words[i].length * words[j].length);
}
}
}
return maxProd;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-product-of-word-lengths