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.

解题思路:需要作出两个判断。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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值