Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.
Example 1:
Input: words = [“abcw”,“baz”,“foo”,“bar”,“xtfn”,“abcdef”]
Output: 16
Explanation: The two words can be “abcw”, “xtfn”.
Example 2:
Input: words = [“a”,“ab”,“abc”,“d”,“cd”,“bcd”,“abcd”]
Output: 4
Explanation: The two words can be “ab”, “cd”.
string数组中找出两个单词,使它们长度的积最大。
但是这两个单词不能包含相同的字母。
思路:
如果没有不能包含相同字母这条限制,
做法应该是找出长度最大的前2个单词,把它们的长度相乘。
所以现在任务转变为如何判断两个单词是否含有相同的字母。
每次都一个一个比较太麻烦。
注意到字母一共就只有26个,如果能用26个bit位表示每个单词是否含有这26个字母,
比较的时候bit与一下,结果是0就说明这2个单词没有相同的字母。
所以第一步,用bit位表示每个单词是否含有26个字母,
第2步,bit与的结果为0时,取长度积的最大值。
public int maxProduct(String[] words) {
int n = words.length;
int[] masks = new int[n];
int res = 0;
for(int i = 0; i < n; i ++) {
for(int k = 0; k < words[i].length(); k++) {
masks[i] |= (1 << words[i].charAt(k) - 'a');
}
}
for(int i = 0; i < n-1; i++) {
for(int j = i+1; j < n; j++) {
if((masks[i] & masks[j]) == 0) {
res = Math.max(res, words[i].length() * words[j].length());
}
}
}
return res;
}