Leetcode 318. Maximum Product of Word Lengths

Problem

Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.

Algorithm

Use a mask variable to determine whether there are common letters, and then calculate the result through iteration.

Code

class Solution:
    def maxProduct(self, words: List[str]) -> int:
        word_size = len(words)
        masks = [0] * word_size
        lengths = [0] * word_size
    
        for i in range(word_size):
            for c in words[i]:
                masks[i] |= 1 << (ord(c) - ord('a'))
            lengths[i] = len(words[i])

        ans = 0
        for i in range(word_size):
            for j in range(i+1, word_size):
                if masks[i] & masks[j] == 0:
                    ans = max(ans, lengths[i] * lengths[j])

        return ans

你可能感兴趣的:(解题报告,入门题,leetcode,word,算法)