目录

0318:最大单词长度乘积(★)

力扣第 318 题

题目

给你一个字符串数组 words ,找出并返回 length(words[i]) * length(words[j]) 的最大值,并且这两个单词不含有公共字母。如果不存在这样的两个单词,返回 0

示例 1:

输入:words = ["abcw","baz","foo","bar","xtfn","abcdef"]
输出:16
解释这两个单词为 "abcw", "xtfn"

示例 2:

输入:words = ["a","ab","abc","d","cd","bcd","abcd"]
输出:4
解释这两个单词为 "ab", "cd"

示例 3:

输入:words = ["a","aa","aaa","aaaa"]
输出:0
解释不存在这样的两个单词。

提示:

  • 2 <= words.length <= 1000
  • 1 <= words[i].length <= 1000
  • words[i] 仅包含小写字母

分析

#1

先保存每个单词的字母集合,然后遍历每一对单词,判断是否有公共字母即可。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def maxProduct(self, words: List[str]) -> int:
        n = len(words)
        A = [sum(1<<(ord(c)-ord('a')) for c in set(w)) for w in words]
        res = 0
        for i in range(n):
            for j in range(i+1,n):
                if A[i]&A[j]==0:
                    res = max(res,len(words[i])*len(words[j]))
        return res

238 ms

#2

注意到可能有多个单词的字母集合相同,可以只保留最大长度。

解答

1
2
3
4
5
6
7
class Solution:
    def maxProduct(self, words: List[str]) -> int:
        d = defaultdict(int)
        for w in words:
            st = sum(1<<(ord(c)-ord('a')) for c in set(w))
            d[st] = max(d[st], len(w))
        return max([d[a]*d[b] for a in d for b in d if not a&b], default=0)

103 ms