1-liner in Python with bit masking


  • 0
    O
    class Solution(object):
        def maxProduct(self, words):
            return max([n1*n2 for (n1,b1),(n2,b2) in itertools.combinations(map(lambda x:(len(x),sum(1<<(ord(c)-ord('a')) for c in set(x))),words),2) if b1&b2==0] or [0])
    

    which is equivalent to:

    class Solution(object):
        def maxProduct(self, words):
            def f(w):
                return sum(1<<(ord(c)-ord('a')) for c in set(w))
            l = map(f, words)
            return max([len(words[i])*len(words[j]) for i,j in itertools.combinations(range(len(words)),2) if l[i]&l[j]==0] or [0])
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.