function judge(word1,word2)
{
let set1=[];
let set2=[];
for(let i=0;i<word1.length;i++)
{
set1[word1.charCodeAt(i)-96] = 1;
}
for(let i=0;i<word2.length;i++)
{
set2[word2.charCodeAt(i)-96] = 1;
}
for(let i=0;i<26;i++)
{
if(set1[i]&&set2[i]) return false;
}
return true;
}
var maxProduct = function(words) {
let res=0;
for(let i=0;i<words.length;i++)
{
for(let j=i+1;j<words.length;j++)
{
if(judge(words[i],words[j]))
{
res=Math.max(words[i].length*words[j].length,res);
}
}
}
return res;
};
官方方法:
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;
};
注意事项:
- 位运算的思路
- 字母和数字映射
- 左右移动符号