Python accepted solution


  • 5
    M

    Not very efficient though

    class Solution(object):
        def maxProduct(self, words):
            """
            :type words: List[str]
            :rtype: int
            """
            if not words:
                return 0
            curr_max = 0
            while words:
                curr_word = set(words[0])
                curr_len = len(words[0])
                words = words[1:]
                for word in words:
                    for char in curr_word:
                        if char in word:
                            break
                    else:
                        curr_max = max(curr_max, curr_len*len(word))
            return curr_max

  • 0
    C
    class Solution(object):
        def maxProduct(self, words):
            """
            :type words: List[str]
            :rtype: int
            """
            res = 0
            for i in xrange(len(words)):
                for j in xrange(i + 1, len(words)):
                    temp = set(words[i])
                    templen = len(words[i])
                    for char in temp:
                        if char in set(words[j]):
                            break
                    else:
                        res = max(res, templen * len(words[j]))
            return res
    

    What is different between my solution and yours?
    I can not figure out. Cloud you please tell my?


  • 1
    I

    Your code will go over the time limit. This does the trick: curr_word = set(words[0]): it removes duplicate digits.


  • 0
    W

    @luke.liu.585 I was writing similar codes to yours. This might do the trick - instead of generate a set() in every iteration, generate a list of set at beginning and refer to it

    class Solution(object):
        def maxProduct(self, words):
            """
            :type words: List[str]
            :rtype: int
            """
            maxres = 0
            n = len(words)
            wordsset = [set(i) for i in words]
            for i in range(n):
                for j in range(i+1,n):
                    for char in wordsset[j]:
                        if char in wordsset[i]:
                            break
                    else:
                        maxres = max(maxres, len(words[i])*len(words[j]))
            return maxres
    

Log in to reply
 

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