[leetcode] 318. Maximum Product of Word Lengths
2016-08-04 11:53
417 查看
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.
解法一:
一开始以为有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;
}
};
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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解