0
点赞
收藏
分享

微信扫一扫

leetcode(力扣) 318. 最大单词长度乘积 (利用集合模拟过程)


题目在这:​​https://leetcode-cn.com/problems/maximum-product-of-word-lengths/​​

思路分析:

找到最长的两个单词,且两个单词之间不能有互相包含的字母。
可以利用集合的性质判断两个单词中是否有互相包含的字母。
但要注意,单个字符本身是可以有重复单词的。
比如 aba 和dfd 这样是可以的。

比如 a和b串进行比较,则 set(a)+set(b)的长度和 set(a+b)的长度,如果一样则说明没有互相包含的字符。

然后两层循环遍历,再遍历过程中,如果不相互包含字母,则记录当前最大的长度。

完整代码

class Solution:
def maxProduct(self, words: List[str]) -> int:
s = words
res = 0
for i in range(len(s)-1):
for j in range(i+1,len(s)):
temp = ''.join(set(s[i])) + ''.join(set(s[j])) # 集合变为字符串格式~
temp_set = set(s[i]+s[j])
if len(temp) == len(temp_set):
res = max(res,len(s[i]) * len(s[j]))
return


举报

相关推荐

0 条评论