Maximum Product of Word Lengths(Medium)
Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
Example 1:
Given [“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”]
Return 16,The two words can be “abcw”, “xtfn”.
Example 2:
Given [“a”, “ab”, “abc”, “d”, “cd”, “bcd”, “abcd”] Return 4 The two words can be “ab”, “cd”.
Example 3:
Given [“a”, “aa”, “aaa”, “aaaa”] Return 0 No such pair of words.
解题思路: 因为每个字母都是小写字母,所以我们可以用一个int的26位去保存每个单词所包含的字母的信息:因为我们不关心每个单词中各个字母出现的个数,只关心是否出现,所以可以用1表示出现,0表示未出现。这样的好处是,经过这样的预处理之后,当需要判断两个单词是否有相同字母时,做个与计算就知道结果了(是否为0)。这样,我们就得到了O(n*n)的解法。
public int maxProduct(String[] words) {
int[] wordMask = new int[words.length];
for (int i = 0; i < words.length; i++) {
wordMask[i] = 0;
String word = words[i];
for (char c : word.toCharArray()) {
wordMask[i] = wordMask[i] | (1 << (c - 'a'));
}
}
int max = 0;
for (int i = 0; i < wordMask.length - 1; i++) {
for (int j = i+1; j < wordMask.length; j++) {
if ((wordMask[i] & wordMask[j]) == 0) {
int tmp = words[i].length() * words[j].length();
if (max < tmp) {
max = tmp;
}
}
}
}
return max;
}