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
3. Time & Space Complexity
时间复杂度O(n^2), 空间复杂度O(n)
Last updated