318. Maximum Product of Word Lengths

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了318. Maximum Product of Word Lengths相关的知识,希望对你有一定的参考价值。

好久没leetcode一下了,以后每天1题,坚持一下~

https://leetcode.com/problems/maximum-product-of-word-lengths/


Total Accepted: 9706 Total Submissions: 24927 Difficulty: Medium
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".

 

sol: 将每个单词对应到一个数。为增加效率,长度也可提前算好。

class Solution(object):
    def maxProduct(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        n = len(words)
        word_map,len_map = [],[]
        for word in words:
            word_map += sum(1<<(ord(x)-ord(a)) for x in set(word)),
            len_map += len(word),
        
        ans = 0
        for i in range(n):
            for j in range(i+1,n):
                if word_map[i] & word_map[j] == 0:
                    ans = max( len_map[i]*len_map[j], ans )
        
        return ans                              
            

 

以上是关于318. Maximum Product of Word Lengths的主要内容,如果未能解决你的问题,请参考以下文章

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

LeetCode 318. Maximum Product of Word Lengths