zoukankan      html  css  js  c++  java
  • 边工作边刷题: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
                
    
    
  • 相关阅读:
    选择适合什么模式
    Filter做用户授权的例子
    分析LogFilter
    理解session
    XML定义用途
    web服务后台应用工作原理
    企业级应用和互联网应用的区别
    轻量级Java EE企业应用实战的目标
    软件工程期末项目总结
    软件工程之学习报告
  • 原文地址:https://www.cnblogs.com/absolute/p/5690313.html
Copyright © 2011-2022 走看看