本题是找出数组中最长的所有字母都不一样的两个单词,返回他们的长度乘积,不存在返回零。
思路:新建一个数组,将其字母的值转化成相应位置二进制数值为1,并将他们相与,结果为0,就返回他们长度的乘机,时间复杂度为0(n2),空间复杂度为0(n)。
代码如下:
class Solution {
public int maxProduct(String[] words) {
int l= words.length;
int max = 0;
int[] tag = new int[l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < words[i].length(); j++) {
tag[i] |= 1<<(words[i].charAt(j)-'a') ;
}
}
for (int i = 0; i < l; i++) {
for (int j = i+1; j < l; j++) {
if((tag[i]&tag[j])==0){
max = Math.max(max, words[i].length()*words[j].length());
}
}
}
return max;
}
}