Maximum Product of Word Lengths
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.
- Time: O(n)
- Space: O(1)
public int maxProduct(String[] words) {
int[] masks = new int[words.length];
int max = 0;
for (int i = 0; i < words.length; i++) {
for (char c : words[i].toCharArray()) {
masks[i] |= 1 << c - 'a';
}
for (int j = 0; j < i; j++) {
if ((masks[i] & masks[j]) == 0) {
max = Math.max(max, words[i].length() * words[j].length());
}
}
}
return max;
}