318. Maximum Product of Word Lengths
好久没leetcode一下了,以后每天1题,坚持一下~
https://leetcode.com/problems/maximum-product-of-word-lengths/
Total Accepted: 9706 Total Submissions: 24927 Difficulty: Medium 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. Example 1: Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] Return 16 The two words can be "abcw", "xtfn". Example 2: Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] Return 4 The two words can be "ab", "cd".
sol: 将每个单词对应到一个数。为增加效率,长度也可提前算好。
class Solution(object): def maxProduct(self, words): """ :type words: List[str] :rtype: int """ n = len(words) word_map,len_map = [],[] for word in words: word_map += sum(1<<(ord(x)-ord('a')) for x in set(word)), len_map += len(word), ans = 0 for i in range(n): for j in range(i+1,n): if word_map[i] & word_map[j] == 0: ans = max( len_map[i]*len_map[j], ans ) return ans
每天一小步,人生一大步!Good luck~