318 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.
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.
Straight forward solution...
class Solution {
public:
bool shareCommon(string s1, string s2) {
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
int i1 = 0, i2 = 0;
int n1 = s1.size(), n2 = s2.size();
while ( i1 < n1 and i2 < n2 ) {
if ( s1[i1] == s2[i2] ) return true;
if ( s1[i1] > s2[i2] ) i2++;
else i1++;
}
return false;
}
int maxProduct(vector<string>& words) {
int n = words.size();
int res = 0;
for ( int i = 0; i < n-1; i++ ) {
for ( int j = i+1; j < n; j++ ) {
if ( not shareCommon(words[i], words[j]) ) res = max(res, int(words[i].size() * words[j].size()));
}
}
return res;
}
};
Bit-manipulation solution
class Solution {
public:
int toInt(string s) {
int n = s.size();
int res = 0;
for ( int i = 0; i < n; i++ ) res |= (1 << s[i]-'a');
return res;
}
int maxProduct(vector<string>& words) {
int n = words.size(), res = 0;
vector<int> nums;
for ( int i = 0; i < n; i++ ) nums.push_back(toInt(words[i]));
for ( int i = 0; i < n-1; i++ ) {
for ( int j = i+1; j < n; j++ ) {
if ( (nums[i]&nums[j]) == 0 ) res = max(res, int(words[i].size()*words[j].size()));
}
}
return res;
}
};