【leetcode题解】【M】【10】318. Maximum Product of Word Lengths
2015-12-23 01:28
441 查看
Given a string array
Example 1:
Given
Return
The two words can be
Example 2:
Given
Return
The two words can be
Example 3:
Given
Return
No such pair of words.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
最开始用 集合做,不过太慢了
然后看到可以用位操作,把每个字符串,转成一个26位的 bit串,关键是 用 | 来
然后对每个bit串,互相之间进行取 & 操作,如果为0,则说明没有重复的字母
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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
最开始用 集合做,不过太慢了
然后看到可以用位操作,把每个字符串,转成一个26位的 bit串,关键是 用 | 来
然后对每个bit串,互相之间进行取 & 操作,如果为0,则说明没有重复的字母
class Solution(object): def maxProduct(self, words): #bit = [0] maxx = 0 bit = [0] * len(words) for i in xrange(len(words)): for j in words[i]: bit[i] |= 1 << (ord(j) - ord('a')) #print bit for i in xrange(len(bit)): for j in xrange(i+1,len(bit)): #print i,j if len(words[i])*len(words[j])< maxx: continue if bit[i] & bit[j] == 0: maxx = max(maxx,len(words[i])*len(words[j])) return maxx ''' pay attention to those like 'aaa',when using set it's too slow for i in xrange(len(words)): for j in xrange(i+1,len(words)): a = set(words[i]) b = set(words[j]) s = set(words[i] + words[j]) if len(s) ==(len(a)+len(b)): maxx = max(maxx,len(words[i])*len(words[j])) '''
相关文章推荐
- hadoop安装包的目录结构
- 315. Count of Smaller Numbers After Self
- POJ 1088 滑雪
- 温伯格技术思想三部曲:颠覆完美软件(4)
- Android动态广播添加权限
- Good Bye2015,Hello 2016
- 阻止元素被选中
- CSS属性(常用的属性)
- iOS.ReactNative-5-make-react-native-to-support-dynamically-update
- 解决一些网站文字不能复制的问题?java应用
- Netty4 HTTP请求参数解析(GET, POST)
- Docker系列三
- 电脑随机数是如何生成的?
- striving for simplicity:the all convolutional net
- cygwin(x64) 下编译 redis
- Java 注解
- C-语言-detail(上)
- Java Script基础(十二) 正则表达式
- 中位数求和 BUAA214 大新闻
- Java Script基础(十一) 表单验证