Skip to content

Instantly share code, notes, and snippets.

@Liam0205
Created January 23, 2016 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Liam0205/9ddf03191d6af5e34001 to your computer and use it in GitHub Desktop.
Save Liam0205/9ddf03191d6af5e34001 to your computer and use it in GitHub Desktop.
inline bool stringLengthLarger (const string & lhs, const string & rhs) {
return lhs.length() > rhs.length();
}
class Solution {
public:
int maxProduct(vector<string>& words) {
size_t sz_words = words.size();
if (sz_words < 2) {
return 0;
}
sort (words.begin(), words.end(), stringLengthLarger);
vector<int> mask (sz_words, 0);
for (size_t i = 0; i != sz_words; ++i) {
const string & curr = words[i];
size_t sz_curr = curr.length();
int & curr_mask = mask[i];
for (size_t j = 0; j != sz_curr; ++j) {
curr_mask |= 1 << (curr[j] - 'a');
}
}
int curr_max = 0;
for (size_t i = 0, range = sz_words - 1; i != range; ++i) {
for (size_t j = i + 1; j != sz_words; ++j) {
if (!(mask[i] & mask[j])) {
int curr = words[i].length() * words[j].length();
curr_max = max (curr_max, curr);
range = min (range, j);
break;
}
}
}
return curr_max;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment