Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.python
Example 1:git
Input: ["abcw","baz","foo","bar","xtfn","abcdef"] Output: 16 Explanation: The two words can be "abcw", "xtfn".
Example 2:github
Input: ["a","ab","abc","d","cd","bcd","abcd"] Output: 4 Explanation: The two words can be "ab", "cd".
Example 3:數組
Input: ["a","aa","aaa","aaaa"] Output: 0 Explanation: No such pair of words.
給定一個字符串數組 words,找到 length(word[i]) * length(word[j]) 的最大值,而且這兩個單詞不含有公共字母。你能夠認爲每一個單詞只包含小寫字母。若是不存在這樣的兩個單詞,返回 0。ui
示例 1:code
輸入: ["abcw","baz","foo","bar","xtfn","abcdef"] 輸出: 16 解釋: 這兩個單詞爲 "abcw", "xtfn"。
示例 2:ip
輸入: ["a","ab","abc","d","cd","bcd","abcd"] 輸出: 4 解釋: 這兩個單詞爲 "ab", "cd"。
示例 3:utf-8
輸入: ["a","aa","aaa","aaaa"] 輸出: 0 解釋: 不存在這樣的兩個單詞。
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-02-23 13:14:24 # @Last Modified by: 何睿 # @Last Modified time: 2019-02-23 14:24:48 import itertools class Solution: def maxProduct(self, words) -> int: # bits 是字典,鍵爲單詞 word 對應的二進制碼,值爲一個二進制碼對應的最長單詞 # 最長單詞:單詞 a,aa,aaa,aaaa,對應的二進制碼都是 0b1,爲了得到最大的乘積 # 咱們取最長的單詞 aaaa,因此 0b1 對應 4 bits = {} for word in words: # 獲取單詞單詞對應的 二進制碼,有點相似哈希,可是不徹底相同 bit = self.getBit(word) # 創建鍵值對,這樣能夠避免屢次 len(word) # 值爲最長單詞的長度 bits[bit] = max(bits.get(bit, 0), len(word)) # 對一個列表的全部元素進行兩兩組合 # 也能夠用循環,如 maxProduct2 中示例 # 可是在 python 中 itertools.combinations 更快 com = itertools.combinations(bits.keys(), r=2) # 對全部組合中單詞沒有重複的求乘積,這裏也能夠寫成循環的形式 # 可是在 python 中列表解析式的執行速度更快 return max([bits[x] * bits[y] for x, y in com if x & y == 0] or [0]) def maxProduct2(self, words) -> int: res = 0 bits = [self.getBit(word) for word in words] for i in range(len(words)): for j in range(i + 1, len(words)): if bits[i] & bits[j] == 0: res = max(res, len(words[i]) * len(words[j])) return res def getBit(self, word): bit = 0 # 按位或 # 字母 a 對一二進制第 1 位,b 對應第 2 位 ... z 對應 第 26 位 for char in word: bit = bit | (1 << (ord(char) - 97)) return bit