卖萌的弱渣

I am stupid, I am hungry.

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.

Solution

  • element[i]: is 27 bit long, each bit represent word[i][j] - ‘0’
(Maximum-Product-of-Word-Lengths.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
    def maxProduct(self, words):
        """
        :type words: List[str]
        :rtype: int
        """

        elements = [0] * len(words)
        for i,s in enumerate(words):
            for c in s:
                elements[i] |= 1<<(ord(c)-97)
        ret = 0
        for i in range(len(words)):
            for j in range(i+1, len(words)):
                if not (elements[i] & elements[j]):
                    ret = max(ret, len(words[i])*len(words[j]))
        return ret