Problem Statement
(Source) 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.
Solution
class Solution(object):
def maxProduct(self, words):
"""
:type words: List[str]
:rtype: int
"""
res, n = 0, len(words)
nums = [sum(1 << (ord(ch) - ord('a')) for ch in set(words[i])) for i in xrange(n)]
for i in xrange(n - 1):
for j in xrange(i + 1, n):
if nums[i] & nums[j] == 0:
res = max(res, len(words[i]) * len(words[j]))
return res
Complexity analysis:
- Time complexity:
max(O(n2),O(mn))
, where
n
is the number of words, and
m is the average length of all words. - Space complexity: O(n) , where n <script type="math/tex" id="MathJax-Element-102">n</script> is the number of words.