【leetcode】Maximum Product of Word Lengths

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

Example 1:

Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn".

Example 2:

Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return 4
The two words can be "ab", "cd".

Example 3:

Given ["a", "aa", "aaa", "aaaa"]
Return 0
No such pair of words.

此题如果用暴力比较法,也就是两层循环依次比较的话,执行会超时。

可以通过类似C++中bitset的方法来保存每个单词的一个key值,然后直接用key值进行比较,减少单词之间比较的时候比较字符的时间。

比如单词abcw,我们可以创建一个l = [0,0,0.....0] 有27个0的数组,并按26个字母的顺序依次给a-z索引为1~26,最后把a,b,c,w四位对应的元素的值置为1,计算 pow(2,1)+pow(2,2)+pow(2,3)+pow(2,23)的和即为这个元素的key值。

再用这个key值与其他元素的key值做与操作,结果为0,则表示单词无相同的字符。

下面是代码:

class Solution(object):
    index = []
    def transChar(self,c):
        l = [‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘,‘k‘,‘l‘,‘m‘,‘n‘,‘o‘,‘p‘,‘q‘,‘r‘,‘s‘,‘t‘,‘u‘,‘v‘,‘w‘,‘x‘,‘y‘,‘z‘]
        return l.index(c) + 1
    def parseWords(self,w):
        t = 0
        l = []
        for i in range(27):
            l.append(0)
        for i in set(w): #注:这里用set过滤掉相同的字符,我最初直接用w,导致运行超时
            t = self.transChar(i)
            l[t] = 1
        t = 0
        for i in range(len(l)):
            if l[i] == 1:
                t = t + pow(2,i)
        #print w,t
        return t
    def maxProduct(self, words):
        """
        :type words: List[str]
        :rtype: int
        """

        max = 0
        if len(words) == 0:
            return 0
        l = []
        for i in words:
            l.append(self.parseWords(i))

        for i in range(len(l)):
            for j in range(i+1,len(l)):
                if l[i] & l[j] == 0:
                    if max < len(words[i]) * len(words[j]):
                        max = len(words[i]) * len(words[j])
        return max
时间: 2024-12-23 08:22:32

【leetcode】Maximum Product of Word Lengths的相关文章

【LeetCode】Maximum Product Subarray 求连续子数组使其乘积最大

Add Date 2014-09-23 Maximum Product Subarray Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4],the contiguous subarray [2,3] has the largest product = 

leetcode 318: Maximum Product of Word Lengths

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0. Example

【Leetcode】Maximum Product Subarray

题目链接:https://leetcode.com/problems/maximum-product-subarray/ 题目: Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has t

Leetcode 318 Maximum Product of Word Lengths 字符串处理+位运算

先介绍下本题的题意: 在一个字符串组成的数组words中,找出max{Length(words[i]) * Length(words[j]) },其中words[i]和words[j]中没有相同的字母,在这里字符串由小写字母a-z组成的. 对于这道题目我们统计下words[i]的小写字母a-z是否存在,然后枚举words[i]和words[j],找出max{Length(words[i]) * Length(words[j]) }. 小写字母a-z是26位,一般统计是否存在我们要申请一个bool

Maximum Product of Word Lengths

Maximum Product of Word Lengths Total Accepted: 750 Total Submissions: 2060 Difficulty: Medium Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume tha

【LeetCode】 Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. More practice: If you have figu

【Leetcode】Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space cha

【LeetCode】 Maximum Depth of Binary Tree

Maximum Depth of Binary Tree  Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 递归基础,不解释. class Solution { public: int getMax(TreeNode *root

【LeetCode】- Length of Last Word(最后一个单词的长度)

[ 问题: ] Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. 给你一个字符串,设法获取它最后一个单词的长度.如果这个单词不存在,则返回0. [ 分析 : ] A word is defined