博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】Maximum Product of Word Lengths
阅读量:7100 次
发布时间:2019-06-28

本文共 1919 字,大约阅读时间需要 6 分钟。

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

 

转载于:https://www.cnblogs.com/seyjs/p/5133241.html

你可能感兴趣的文章
通达OA 小飞鱼开发培训第四讲 工作流介绍(图文)
查看>>
PhoneGap_百度百科
查看>>
bootstrap基础学习六篇
查看>>
[.net 面向对象程序设计深入](5)MVC 6 —— 构建跨平台.NET开发环境(Windows/Mac OS X/Linux)...
查看>>
Android横竖屏切换及其相应布局载入问题
查看>>
带辉光效果的跑马灯
查看>>
CSS隐藏元素的几个方法(display,visibility)的区别
查看>>
HTML 中的 dl(dt,dd)、ul(li)、ol(li)
查看>>
Linux下Redis主从复制以及SSDB主主复制环境部署记录
查看>>
如何让win10实现关机确认-暂没确认
查看>>
常用js函数整理--common.js
查看>>
java内存泄漏与内存溢出
查看>>
分布式与集群
查看>>
互联网服务器的实现过程需要考虑哪些安全问题 & 加解密及哈希知识点
查看>>
sql server2008给数据表,字段,添加修改注释
查看>>
meta标签清理缓存
查看>>
【数据结构】二叉树
查看>>
onvif开发之设备发现功能的实现--转
查看>>
虚拟机下linux迁移造成MAC地址异常处理办法
查看>>
数据库事务原子性、一致性是怎样实现的?[转]
查看>>