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、预运算
用预运算来避免重复计算。