Record problem solution: Likou 318. Maximum word length product

Given an array of strings  words, find and return length(words[i]) * length(words[j]) the maximum value of two words that do not contain a common letter. If no such two words exist, return 0.

Example 1:

input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
output:16 
解释这两个单词为 "abcw", "xtfn"

Example 2:

input: words = ["a","ab","abc","d","cd","bcd","abcd"]
output: : these two words are4 
解释"ab", "cd"

Example 3:

input: words = ["a","aa","aaa","aaaa"]
output:0 
解释不存在这样的两个单词。

Idea: first use set() to deduplicate the words in the list. Then take the intersection of the words in the list.

class Solution:
    def maxProduct(self, words: List[str]) -> int:
        a = [set(word) for word in words]
        ans = 0
        for i in range(len(a)):
            for j in range(i+1 , len(a)):
                if not a[i].intersection(a[j]):
                    ans = max(ans, len(words[i]) * len(words[j]))
        return ans

Note: The intersection() function is used to take the intersection

Guess you like

Origin blog.csdn.net/weixin_45314061/article/details/130535091