题目:
给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。
思路
26位的int 每一位当作一个字母,1表示存在这个字母,0表示没有。 因为值只包含小写字母。
// int类型最多可以表 32位状态,字母只有小写,所以最多26位即可满足
// a b c d e f g h (agh) 1即表示拥有这个字母,顺序or数量无所谓
// 1 0 0 0 0 0 1 1
// a b c d e f g h (bcde) 1即表示拥有这个字母,顺序or数量无所谓
// 0 1 1 1 1 0 0 0
代码
class Solution {
public int maxProduct(String[] words) {
int max = 0;
int[] maxs = new int[words.length];
for (int i = 0; i < words.length; i++) {
String str = words[i];
for (int i1 = 0; i1 < str.length(); i1++) {
// a在0号比特位,依次类推
maxs[i] |= 1 << str.charAt(i1) - 'a';
}
}
for (int i = 0; i < maxs.length; i++) {
for (int j = i + 1; j < maxs.length; j++) {
// 按位与
if ((maxs[i] & maxs[j]) == 0){
max = Math.max(words[i].length() * words[j].length(),max);
}
}
}
return max;
}
}