[LeetCode 318] Maximum Product of Word Lengths(Python)

来源:互联网 发布:moe破解软件下载 编辑:程序博客网 时间:2024/06/06 12:30

题目描述

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.

思路

本题要找到数组中两个最长的且没有公共字母的字符串。如果有暴力解法,时间复杂度过高,而且代码也不简洁。因为每个字符串都是由26个字母组成的,所以我们可以考虑先对每个字符串编码,可以利用位运算进行编码,出现的字母对应位置一。然后判断两个字符串有没有公共字符只需判断它们对应的编码的与运算是否为1即可。

代码

class Solution(object):    def maxProduct(self, words):        """        :type words: List[str]        :rtype: int        """        if words is None or len(words) <= 1:            return 0        codes = []        for i in words:            tmp = 0            for j in list(i):                tmp |= 1 << (ord(j) - ord('a'))            codes.append(tmp)        res = 0        for i in range(len(codes)):            for j in range(i + 1, len(codes)):                if codes[i] & codes[j] == 0:                    res = max(res, len(words[i]) * len(words[j]))        return res

复杂度分析

时间复杂度O(n2),空间复杂度O(n)

原创粉丝点击