Leetcode 318.最大单词长度乘积(Maximum Product of Word Lengths)

Leetcode 318.最大单词长度乘积

1 题目描述(Leetcode题目链接)

  给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。

输入: ["abcw","baz","foo","bar","xtfn","abcdef"]
输出: 16 
解释: 这两个单词为 "abcw", "xtfn"
输入: ["a","ab","abc","d","cd","bcd","abcd"]
输出: 4 
解释: 这两个单词为 "ab", "cd"
输入: ["a","aa","aaa","aaaa"]
输出: 0 
解释: 不存在这样的两个单词。

2 题解

  利用集合的交集操作,暴力求解。

class Solution:
    def maxProduct(self, words: List[str]) -> int:
        res = 0
        for i in range(len(words)):
            for j in range(i+1, len(words)):
                if not set(words[i]) & set(words[j]):
                    res = max(res, len(words[i])*len(words[j]))
        return res

利用位运算,将单词映射到26位的二进制数,每个位对应字母是否出现。这样判断两个字母是否有公共字母就只需要判断它们的二进制与操作后是否为零就好了。这样的思想还挺好的,不方便操作的元素可以通过映射到我们熟悉的域来操作。

class Solution:
    def maxProduct(self, words: List[str]) -> int:
        hashmap = collections.defaultdict(int)
        for word in words:
            bitmap = 0
            for c in word:
                bitmap |= 1 << ord(c) - ord('a')
            hashmap[bitmap] = max(hashmap[bitmap], len(word))
        max_p = 0
        for k1 in hashmap:
            for k2 in hashmap:
                if k1 & k2 == 0:
                    max_p = max(max_p, hashmap[k1] * hashmap[k2])
        return max_p

你可能感兴趣的:(Leetcode,leetcode,算法)