一、题目地址
https://leetcode-cn.com/problems/aseY1I/
二、具体代码
/**
* @param {string[]} words
* @return {number}
*/
// 1、暴力解法
// m 表示单词的平均长度,n 表示单词的个数
// 时间复杂度:O(n^2 * m)
// 空间复杂度:O(1)
var maxProduct = function(words) {
let res = 0;
for(let i=0; i<words.length; i++) {
let word1 = words[i];
for(let j=i+1; j<words.length; j++) {
let word2 = words[j];
if(!hasSameLetter(word1, word2)) {
res = Math.max(res, word1.length * word2.length);
}
}
}
return res;
};
function hasSameLetter(word1, word2) {
for(let i=0; i<word1.length; i++) {
if(word2.indexOf(word1[i]) !== -1) {
return true;
}
}
return false;
}
/**
* @param {string[]} words
* @return {number}
*/
// 2、暴力法——时间复杂度O(m * n^2),空间复杂度O(1)
var maxProduct = function(words) {
let res = 0;
for(let i=0; i<words.length; i++) {
let word1 = words[i];
for(let j=i+1; j<words.length; j++) {
let word2 = words[j];
if(!hasSameLetter(word1, word2)) {
res = Math.max(res, word1.length * word2.length);
}
}
}
return res;
};
//hasSameLetter()方法优化,时间复杂度O(m),空间复杂度O(1)
function hasSameLetter(word1, word2) {
let count = new Array(26).fill(0);//26个字母的空间,空间复杂度依旧是O(1)
for(let c of word1) {
count[c.charCodeAt() - 'a'.charCodeAt()] = 1;
}
for(let c of word2) {
if(count[c.charCodeAt() - 'a'.charCodeAt()] === 1) {
return true;
}
}
return false;
}
/**
* @param {string[]} words
* @return {number}
*/
// 3、位运算 + 预计算
// 时间复杂度:O((m + n)* n)
// 空间复杂度:O(n)
var maxProduct = function(words) {
let bitMap = new Map();
for(let i=0; i<words.length; i++) {
let bitMask = 0;
for(let c of words[i]) {
bitMask |= (1 << c.charCodeAt() - 'a'.charCodeAt());
}
if(!bitMap.has(bitMask)) {
bitMap.set(bitMask, words[i].length);
}else {
bitMap.set(bitMask, Math.max(bitMap.get(bitMask), words[i].length));
}
}
let res = 0;
for(let key1 of bitMap.keys()) {
for(let key2 of bitMap.keys()) {
if((key1 & key2) === 0) {
res = Math.max(res, bitMap.get(key1) * bitMap.get(key2));
}
}
}
return res;
};
三、补充链接
https://leetcode-cn.com/problems/aseY1I/solution/jian-dan-yi-dong-javac-pythonjs-zui-da-d-ffga/