318. Maximum Product of Word Lengths
from collections import defaultdict
class Solution:
def maxProduct(self, words: List[str]) -> int:
hashmap = defaultdict(int)
bit_number = lambda ch: ord(ch) - ord('a')
for word in words:
bitmask = 0
for ch in word:
# add bit number bit_number in bitmask
bitmask |= 1 << bit_number(ch)
# there could be different words with the same bitmask
# ex. ab and aabb
hashmap[bitmask] = max(hashmap[bitmask], len(word))
max_prod = 0
for x in hashmap:
for y in hashmap:
if x & y == 0:
max_prod = max(max_prod, hashmap[x] * hashmap[y])
return max_prod
方法小结:
1、位掩码:
用整数的低26位来代替单词中是否包含相应的字母;当两个单词中包含相同字母时,他们的掩码相与不为0。
2、预运算
用预运算来避免重复计算。
本文介绍了一种利用位掩码技巧解决字符串问题的方法,通过计算单词中字母的二进制表示,找出具有相同特征的单词组合,从而找到最大长度单词乘积。通过预运算减少重复计算,提升算法效率。
304

被折叠的 条评论
为什么被折叠?



