给定一个字符串数组 words,请计算当两个字符串 words[i] 和 words[j] 不包含相同字符时,它们长度的乘积的最大值。假设字符串中只包含英语的小写字母。如果没有不包含相同字符的一对字符串,返回 0。
class Solution {
public int maxProduct(String[] words) {
int len = words.length;
int[] masks = new int[len];
for(int i=0; i<len; i++){
int temp=0;
for(char c : words[i].toCharArray()){
temp |= 1 << c - 'a'; // 不写成 mask[i] |= 1 << c - 'a'; 是因为这样写会导致每轮内层循环都会读写一次数组的第i个位置上的值,运行时间增加;优化手段:空间换时间。
}
masks[i] = temp;
}
int max = 0;
for(int i=0; i<len; i++){
for(int j=i+1; j<len; j++){
if((masks[i]&masks[j])==0)
max = Math.max(max, words[i].length()*words[j].length());
}
}
return max;
}
}