给定一个字符串数组 words,请计算当两个字符串 words[i] 和 words[j] 不包含相同字符时,它们长度的乘积的最大值。假设字符串中只包含英语的小写字母。如果没有不包含相同字符的一对字符串,返回 0。
示例 1:
输入: words = ["abcw","baz","foo","bar","fxyz","abcdef"]
输出: 16
解释: 这两个单词为 "abcw", "fxyz"。它们不包含相同字符,且长度的乘积最大。
示例 2:
输入: words = ["a","ab","abc","d","cd","bcd","abcd"]
输出: 4
解释: 这两个单词为 "ab", "cd"。
示例 3:
输入: words = ["a","aa","aaa","aaaa"]
输出: 0
解释: 不存在这样的两个单词。
class Solution:
def maxProduct(self, words: List[str]) -> int:
# 方法一
n = len(words)
mask = [0 for _ in range(n)]
for i in range(n):
for j in range(len(words[i])):
mask[i] |= 1 << (ord(words[i][j]) - ord('a'))
ans = 0
for i in range(n-1):
for j in range(i+1,n):
if mask[i] & mask[j] == 0:
ans = max(len(words[i]) * len(words[j]), ans)
return ans
# 方法二
# res = 0
# for i in range(len(words)):
# for j in range(i+1, len(words)):
# if len(list(set(words[i]) & set(words[j]))) == 0:
# res = max(res, len(words[i]) * len(words[j]))
# return res
剑指 Offer(专项突击版)- 剑指 Offer II 005. 单词长度的最大乘积 (20220712)
最新推荐文章于 2022-09-22 11:34:16 发布