Given A string array
words
, find the maximum value of
length(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"]
Return16
The both words can be "abcw", "xtfn"
.
Example 2:
Given["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return4
The both words can be "ab", "cd"
.
Example 3:
Given["a", "aa", "aaa", "aaaa"]
Return0
No such pair of words.
Hide TagsBit Manipulation
Public classSolution { Public intmaxproduct (string[] words) {intMax = 0; //sort the array based on string length in a descending order.Arrays.sort (words,NewComparator<string>() {@Override Public intCompare (String A, string b) {returnB.length ()-a.length (); } }); //get the spectrum for each word. int[] spectrum =New int[Words.length]; for(intw = 0; w<words.length; ++W) {String word=Words[w]; for(inti = 0; I<word.length (); ++i) {spectrum[w]|= 1<<word.charat (i)-' a ';//1<<32 <==> 1<<0-the cycle. } } for(inti = 0; i<words.length-1; ++i) {intL =words[i].length (); if(L*l <=max) Break; for(intj = i+1; j<words.length; ++j) {if((Spectrum[i] & spectrum[j]) = = 0) {Max= Math.max (max, l*words[j].length ()); Break; } } } returnMax; }}
318. Maximum Product of Word Lengths