边工作边刷题:70天一遍leetcode: day 51

Maximum Product of Word Lengths

要点:一开始的方法想错了,以为可以用并查集做,把凡是有相同char的word放到同一组中,然后在不同的组之间做乘法。但是后来发现这个想法有bug,比如ab,bc,cd是同一组,但是ab和cd也可以做乘法。所以并查集的适用条件是所有元素要共享某种条件(当然这种共享条件在前面process的时候不一定available),而不是两两之间。
另一种方法是用intersection:还是先encode每个string(26位bitset),然后用es[c]表示不包含c的word集合。这样就可以避免内层循环来找不相交的word,而是所有当前字符的不存在集合的交集中找即可。复杂度降低了点,但实际上code更花时间。只需要记住方法。

class Solution(object):
    def maxProduct(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        es = []
        for w in words:
            es.append(sum(1 << (ord(c)-ord('a')) for c in set(w))) # error 1: not using set(w), wrong ["a","aa","aaa","aaaa"]
        
        maxLen = 0
        for i in xrange(len(words)-1):
            for j in xrange(i+1, len(words)):
                if not (es[i] & es[j]):
                    if maxLen<len(words[i])*len(words[j]):
                        maxLen = len(words[i])*len(words[j])
        
        return maxLen
            

posted @ 2016-06-23 04:17  absolute100  阅读(78)  评论(0编辑  收藏  举报