Given A string array words
, find the maximum value of the where the words does not length(word[i]) * length(word[j])
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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
1 Public classSolution {2 Public intmaxproduct (string[] words) {3 intAns = 0;4 int[] Bitmap =New int[words.length];5 6 for(inti = 0; i < words.length; i++){7 for(intj = 0; J < Words[i].length (); J + +){8Bitmap[i] |= 1 << (Words[i].charat (j)-' a ');9 }Ten } One A for(inti = 0; i < bitmap.length; i++){ - for(intj = i+1; J < Bitmap.length; J + +){ - if((Bitmap[i] & bitmap[j]) = = 0 && words[i].length () *words[j].length () >ans) { theans = words[i].length () *words[j].length (); - } - } - } + - returnans; + } A}
Have not done a similar topic before, the topic to find out the string array of two not a single letter of the same string product of the maximum value, learned the practice of the great God.
There are only 26 letters, and an int in Java has 32 bits.
by Bitmap[i] |= 1 << (Words[i].charat (j)-' a '), you can record the character of string characters under subscript i.
All of the string features can be recorded again, and then the two loops can be answered.
318. Maximum Product of Word lengths Java Solutions