Given A string array words
, find the maximum value oflength(word[i]) * length(word[j])
where the words does not share common letters. You may assume this each word would contain only lower case letters. If no such and words exist, return 0.
Example 1:
Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The words can be"abcw", "xtfn"
.
Example 2:
Given ["a", "ab", "abc","d", "cd", "bcd", "abcd"]
Return 4
The words can be"ab", "cd"
.
Example 3:
Given ["a", "aa", "aaa","aaaa"]
Return 0
No such pair of words.
Credits:
Special thanks to @dietpepsi for adding this problem and creatingall test cases.
subscribe   to see which companies asked Thisquestion
Idea: Use the Bitmap method to convert a string to a number. For each character in the string ch, convert to 1<< (ch-' a '). As long as the number of two strings after the conversion & operation result is 0, the two strings do not have the same characters. You can find the product of the lengths of the two strings, and the value to be returned by RET, to ensure that RET has always been the largest. To simplify the steps, you can first sort the strings by length, with long strings in front. Thus, within the inner loop, as long as the product can be calculated by satisfying the condition, the inner loop terminates immediately, since the subsequent calculation of the product will be less than the product value of the current calculation. Similarly, in an external loop, if ret>= (Words[i].length () *words[i].length ()), then terminate the loop directly, because the product calculated later must be smaller than the RET.
classSolution {Private: Static BOOLcmpstringAstringb) { returnA.length () >b.length (); } Public: intMaxproduct (vector<string>&words) { intSize=words.size (); Sort (Words.begin (), Words.end (), CMP); Vector<int>numbers; for(stringword:words) { intnum=0; for(CharCh:word) {num|=1<< (ch-'a'); } numbers.push_back (num); } intret=0; for(intI=0; i<size-1; i++){ if(Words[i].length () *words[i].length () <=ret) Break; for(intj=i+1; j<size;j++){ intProduct= (Words[i].length () *words[j].length ()); if((numbers[i]&numbers[j]) = =0) {ret=Max (Product,ret); Break; } } } returnret; }};
318. Maximum Product of Word Lengths