## Maximum Product of Word Lengths

### 描述

Given a string array words, find the maximum value of length(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"]

Return 16

The two words can be "abcw", "xtfn".

Example 2:

Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]

Return 4

The two words can be "ab", "cd".

Example 3:

Given ["a", "aa", "aaa", "aaaa"]

Return 0

No such pair of words.

### 解法1

// Maximum Product of Word Lengths
// Time Complexity: O(26n^2), Space Complexity: O(26n)
public class Solution {
public int maxProduct(String[] words) {
final int n = words.length;
final boolean[][] hashset = new boolean[n][ALPHABET_SIZE];

for (int i = 0; i < n; ++i) {
for (int j = 0; j < words[i].length(); ++j) {
hashset[i][words[i].charAt(j) - 'a'] = true;
}
}

int result = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
boolean hasCommon = false;
for (int k = 0; k < ALPHABET_SIZE; ++k) {
if (hashset[i][k] && hashset[j][k]) {
hasCommon = true;
break;
}
}
int tmp = words[i].length() * words[j].length();
if (!hasCommon && tmp > result) {
result = tmp;
}
}
}
return result;
}
private static final int ALPHABET_SIZE = 26;
}

### 解法2

// Maximum Product of Word Lengths
// Time Complexity: O(n^2), Space Complexity: O(n)
public class Solution {
public int maxProduct(String[] words) {
final int n = words.length;
final int[] hashset = new int[n];

for (int i = 0; i < n; ++i) {
for (int j = 0; j < words[i].length(); ++j) {
hashset[i] |= 1 << (words[i].charAt(j) - 'a');
}
}

int result = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int tmp = words[i].length() * words[j].length();
if ((hashset[i] & hashset[j]) == 0 && tmp > result) {
result = tmp;
}
}
}
return result;
}
}