Google
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
1
public class Solution {
2
public int maxProduct(String[] words) {
3
// store the bit representation for each word
4
int[] wordsBit = new int[words.length];
5
6
for (int i = 0; i < words.length; i++) {
7
String curWord = words[i];
8
int bit = 0;
9
// transform each word into bit representation
10
for (int j = 0; j < curWord.length(); j++) {
11
bit |= 1 << (curWord.charAt(j) - 'a');
12
}
13
wordsBit[i] = bit;
14
}
15
16
int max = 0;
17
for (int i = 0; i < wordsBit.length - 1; i++) {
18
for (int j = i + 1; j < wordsBit.length; j++) {
19
// if two word has no common word
20
if ((wordsBit[i] & wordsBit[j]) == 0) {
21
max = Math.max(max, words[i].length() * words[j].length());
22
}
23
}
24
}
25
return max;
26
}
27
}
Copied!

3. Time & Space Complexity

时间复杂度O(n^2), 空间复杂度O(n)