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

Leetcode:Maximum Product of Word Lengths

时间:2016-05-12 16:35:27      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

题目: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.

解题思路:需要作出两个判断。1)两个单词是否有相同字母。2)如果没有相同字母,单词的长度相乘是否最大。

对于1):可以使用一个变量current_word记录下当前需要比较的单词i:

current_word = set(word[i])

再使用循环语句判断其他单词中是否含有current_word中的字母,如果不包含,则计算乘积:

for word in words:
    for char in current_word:
        if char in words:
            break
    else:
        result = max(len(current_word)*len(word),result)

代码:

class Solution(object):
    def maxProduct(self, words):
        result=0
        while words:
            current_word = set(words[0])
            current_lentghe = len(words[0])
            words = words[1:] #对原向量进行变换
        for word in words:
            for char in current_word:
                if char in word:
                    break
            else:
                result = max(result, current_length*len(word))
        return result

解题思路2:对于问题1),我们可以用一个int的26位去保存每个单词所包含的字母的信息:因为我们不关心每个单词中各个字母出现的个数,只关心是否出现,所以可以用1表示出现,0表示未出现。这样的好处是,经过这样的预处理之后,当需要判断两个单词是否有相同字母时,做个与计算就知道结果了(是否为0)。如:

abc=00 0000 0000 0000 0000 0000 0111 
xyz=11 1000 0000 0000 0000 0000 0000

对于python,可使用:
num[i] = sum(1 << (ord(x)-ord(‘a’)) for x in set(words[i]))
创建26位数组,其中 1<

代码2:

class Solution(object):
def maxProduct(self, words):
nums = []
size = len(words)
for w in words:
nums += sum(1 << (ord(x) - ord(‘a’)) for x in set(w)),
ans = 0
for x in range(size):
for y in range(size):
if not (nums[x] & nums[y]):
ans = max(len(words[x]) * len(words[y]), ans)
return ans

代码优化:使用map,reduce

Leetcode:Maximum Product of Word Lengths

标签:

原文地址:http://blog.csdn.net/neoye125/article/details/51364487

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