Maximum Product of Word Lengths

update Aug 5,2017 0:37

LeetCodearrow-up-right

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.

Basic Idea:

这道题要求所有没有相同字符的字符串长度乘积最大值,没有什么简便办法,只有考虑每一对,然后判断是否有相同字符。

判断两字符串是否有相同字符可以使用 Bit Map,因为 int 有 32 位,足以作为一个set来存放26位的信息(每个bit的 0 1 相当于一个字母 存在 或 不存在)。

Java Code: