# 318 Maximum Product of Word Lengths

## 318. [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/description/)

## 1. Question

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.

## 2. Implementation

**(1) Bit Manipulation**

思路: 对每个word的每个character，我们都用bit来表示，这样做得好处是对于两个word，我们只要用位运算的"&"就可以立刻得知两个word有没common character (如果结果是0，说明没有)，根据这个再找出长度乘积最大的两个word

```java
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)
