Created
January 23, 2016 14:39
-
-
Save Liam0205/9ddf03191d6af5e34001 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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