The tough part here is on how to detect whether two words sharing common letters.
As indicate in the question, each word only contains lower case letters 'a' - 'z', we can actually correlate this problem with "in a given string, detect whether there is any duplicates". The difference here is to detect duplicates between two strings.
thus, we can use idea that if two words contains no common letters, their & operation result should be 0.
Example:
['"abc", "de"] -- > [0x111, 0x11000], thus, 0x111 & 0x11000 -> 0.
// I originally thought about to use unordered_map<int, int> to store the getBits and string size. However, it is easy to make problems.
int getBits(string& str) {
int bits = 0;
for(char c : str) {
bits |= (1 << (c - 'a'));
}
return bits;
}
int maxProduct(vector<string>& words) {
int result= 0;
int size = words.size();
vector<int> m(size, 0);
vector<int> n(size, 0);
for(int i = 0; i < size; ++i) {
m[i] = getBits(words[i]);
n[i] = words[i].size();
}
// seems like there is no better method to get the max.....
for(int i = 0; i < size; ++i) {
for(int j = i + 1; j < size; ++j) {
// there is no common letters.
if((m[i] & m[j]) == 0) {
result = max(n[i] * n[j], result);
}
}
}
return result;
}