您的位置:首页 > 其它

[leetcode] 318. Maximum Product of Word Lengths

2016-08-04 11:53 417 查看
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.

解法一:

一开始以为有linear的解法,没有想出来。后来O(n^2)的解法用hash table还是不行。

现在这个思路是把每一个单词转成一个int(32位),出现该字母就将对应的bit置一。如果两个单词具有相同的字母,那么他们的&操作不为0。

class Solution {
public:
int maxProduct(vector<string>& words) {
int res = 0;
int num = words.size();
vector<int> m(num,0);
for(int i=0; i<num;++i){
for(char a:words[i])
m[i] |= 1<<(a-'a');

for(int j=0;j<i;++j){
if((m[i]&m[j])==0){
res = max(res,int(words[i].size()*words[j].size()));
}
}
}
return res;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode medium