318 Maximum Product of Word Lengths
1. Question
2. Implementation
public class Solution {
public int maxProduct(String[] words) {
// store the bit representation for each word
int[] wordsBit = new int[words.length];
for (int i = 0; i < words.length; i++) {
String curWord = words[i];
int bit = 0;
// transform each word into bit representation
for (int j = 0; j < curWord.length(); j++) {
bit |= 1 << (curWord.charAt(j) - 'a');
}
wordsBit[i] = bit;
}
int max = 0;
for (int i = 0; i < wordsBit.length - 1; i++) {
for (int j = i + 1; j < wordsBit.length; j++) {
// if two word has no common word
if ((wordsBit[i] & wordsBit[j]) == 0) {
max = Math.max(max, words[i].length() * words[j].length());
}
}
}
return max;
}
}3. Time & Space Complexity
Last updated