【LeetCode】318. Maximum Product of Word Lengths 解题报告(Python)

【LeetCode】318. Maximum Product of Word Lengths 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/


题目地址:https://leetcode.com/problems/maximum-product-of-word-lengths/description/

题目描述:

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:

Input: ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16 
Explanation: The two words can be "abcw", "xtfn".

Example 2:

Input: ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4 
Explanation: The two words can be "ab", "cd".

Example 3:

Input: ["a","aa","aaa","aaaa"]
Output: 0 
Explanation: No such pair of words.

题目大意

找出两个不包含重复字符的字符串长度乘积最大值。

解题方法

重点是不包含重复字符,显然可以用set统计每个字符串中出现的字符,然后利用O(n2)的时间复杂度暴力求解,竟然过了!

另外好像可以使用位运算的方式,留给二刷吧。

代码如下:

class Solution:
    def maxProduct(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        word_dict = dict()
        for word in words:
            word_dict[word] = set(word)
        max_len = 0
        for i1, w1 in enumerate(words):
            for i2 in range(i1+1, len(words)):
                w2 = words[i2]
                if not (word_dict[w1] & word_dict[w2]):
                    max_len = max(max_len, len(w1) * len(w2))
        return max_len

日期

2018 年 7 月 5 日 ———— 天气变化莫测呀,建议放个伞

猜你喜欢

转载自blog.csdn.net/fuxuemingzhu/article/details/80932597
今日推荐