码迷,mamicode.com
首页 > 其他好文 > 详细

318. Maximum Product of Word Lengths

时间:2016-01-30 13:29:43      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

好久没leetcode一下了,以后每天1题,坚持一下~

https://leetcode.com/problems/maximum-product-of-word-lengths/


Total Accepted: 9706 Total Submissions: 24927 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 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".

 

sol: 将每个单词对应到一个数。为增加效率,长度也可提前算好。

class Solution(object):
    def maxProduct(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        n = len(words)
        word_map,len_map = [],[]
        for word in words:
            word_map += sum(1<<(ord(x)-ord(a)) for x in set(word)),
            len_map += len(word),
        
        ans = 0
        for i in range(n):
            for j in range(i+1,n):
                if word_map[i] & word_map[j] == 0:
                    ans = max( len_map[i]*len_map[j], ans )
        
        return ans                              
            

 

318. Maximum Product of Word Lengths

标签:

原文地址:http://www.cnblogs.com/jkmiao/p/5170772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!