给你一个字符串数组 words ,找出并返回 length(words[i]) * length(words[j]) 的最大值,并且这两个单词不含有公共字母。如果不存在这样的两个单词,返回 0
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-product-of-word-lengths
例:
输入:words = ["abcw","baz","foo","bar","xtfn","abcdef"]
输出:16
解释:这两个单词为 "abcw", "xtfn"。
解析:
将有相同字符的字符串放在同一个key值下,将字符串数组中的字符一一遍历,每一个key值里的进行去重,当前字符串长度乘以剩下的字符串长度,取最大的值即可。
class Solution(object):
def maxProduct(self, words):
"""
:type words: List[str]
:rtype: int
"""
dct = dict() # 创建字典
words = set(words) # 去重
for word in words: # 遍历字符串数组
for c in word: # 遍历字符串的每一个字符
if c not in dct.keys(): # 每一个字符的值为存在该字符的字符串,key值不存在的情况
dct[c] = set() # 创建key
dct[c].add(word) # key值存在则直接将字符串加进去
ans = 0 # 结果
for word in words: # 遍历字符串数组
set_t = set(words) # 去重
for c in word: # 遍历字符串中的字符
set_t -= dct[c] # 去除包含字符“c”的字符串
if len(set_t) == 0: # 所有字符都包括这个字符,不符合提议
continue # 都是重复的,跳过
else:
ans = max(ans, len(word) * max([len(s) for s in set_t])) # 遍历去重后的字符串,当前字符串长度一一乘以剩余字符串长度,取最大值。
return ans # 返回结果