318 Maximum Product of Word Lengths
1. Question
Given a string arraywords
, find the maximum value oflength(word[i]) * length(word[j])
where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
Example 1:
Given["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return16
The two words can be"abcw", "xtfn"
.
Example 2:
Given["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return4
The two words can be"ab", "cd"
.
Example 3:
Given["a", "aa", "aaa", "aaaa"]
Return0
No such pair of words.
2. Implementation
(1) Bit Manipulation
思路: 对每个word的每个character,我们都用bit来表示,这样做得好处是对于两个word,我们只要用位运算的"&"就可以立刻得知两个word有没common character (如果结果是0,说明没有),根据这个再找出长度乘积最大的两个word
public class Solution {
public int maxProduct(String[] words) {
// store the bit representation for each word
int[] wordsBit = new int[words.length];
for (int i = 0; i < words.length; i++) {
String curWord = words[i];
int bit = 0;
// transform each word into bit representation
for (int j = 0; j < curWord.length(); j++) {
bit |= 1 << (curWord.charAt(j) - 'a');
}
wordsBit[i] = bit;
}
int max = 0;
for (int i = 0; i < wordsBit.length - 1; i++) {
for (int j = i + 1; j < wordsBit.length; j++) {
// if two word has no common word
if ((wordsBit[i] & wordsBit[j]) == 0) {
max = Math.max(max, words[i].length() * words[j].length());
}
}
}
return max;
}
}
3. Time & Space Complexity
时间复杂度O(n^2), 空间复杂度O(n)
Last updated
Was this helpful?