题目描述:
?题解一:超时未通过
基本思路:利用set自动去重性质
1.在两个for循环中依次比较words中的两个单词word[i]和word[j]。
2.分别用两个小set保存两个单词中出现的字母,然后用一个大set保存在这两个单词中出现的所有字母,然后判断两个小set长度之和是否等于大set的长度,如果相等,说明没有重复字母,计算长度乘积。
class Solution(object):
def maxProduct(self, words):
word_num = len(words)
maxmul = 0
for i in range(word_num):
for j in range(i+1,word_num):
word1 = words[i]
word2 = words[j]
word_set1 = set()
word_set2 = set()
word_set = set()
for m in range(len(word1)):
word_set1.add(word1[m])
word_set.add(word1[m])
for n in range(len(word2)):
word_set2.add(word2[n])
word_set.add(word2[n])
if len(word_set)==len(word_set1)+len(word_set2):
maxmul = max(maxmul,len(word1)*len(word2))
return maxmul
题解二:题解一改进版 通过
1.为每个单词words[i]用一个set保存出现的字母。
2.对两个单词的set求交集,如果交集为空,则说明没有重复字母。
class Solution(object):
def maxProduct(self, words):
result =[]
maxmul = 0
word_num = len(words)
for word in words:
word_set = set()
for i in range(len(word)):
word_set.add(word[i])
result.append(word_set)
for i in range(word_num):
for j in range(i+1,word_num):
if len(result[i]&result[j])==0:
maxmul = max(maxmul,len(words[i])*len(words[j]))
return maxmul
?题解三:位运算 参考
Leetcode - 318. 最大单词长度乘积 / python题解 / 判断两字符串是否存在相同元素 - 但是我拒绝 - 博客园
用一个26位的二进制数字记录每个word[i]中字母的出现情况。
对两个单词对应的二进制数字进行与运算,如果结果为0,说明没有重复。
class Solution(object):
def maxProduct(self, words):
result = [0] * len(words)
maxmul = 0
for i in range(len(words)):
for j in words[i]:
result[i] |= 1<<(ord(j)-97)
for i in range(len(words)-1):
for j in range(i+1,len(words)):
if not (result[i]&result[j]):
maxmul = max(maxmul,len(words[i])*len(words[j]))
return maxmul
?
|