首页 > 其他 > 详细

318. Maximum Product of Word Lengths

时间:2016-01-30 13:26:42      阅读:277      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!