[LeetCode 318] Maximum Product of Word Lengths
2016-01-12 16:25
411 查看
Given a string array
return 0.
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.
Solution:
Use bit manipulation to mark if two words has shared character, then iterate to check max product
public int maxProduct(String[] words) {
int len = words.length;
if(len <=1 ) return 0;
int[] mask = new int[len];
for(int i=0;i<len;i++) {
for(int j=0;j<words[i].length();j++) {
mask[i] |= 1 << (words[i].charAt(j)-'a');
}
}
int max = 0;
for(int i=0;i<len;i++) {
for(int j=i+1;j<len;j++) {
if((mask[i] & mask[j]) == 0) {
max = Math.max(max, words[i].length() * words[j].length());
}
}
}
return max;
}
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.
Solution:
Use bit manipulation to mark if two words has shared character, then iterate to check max product
public int maxProduct(String[] words) {
int len = words.length;
if(len <=1 ) return 0;
int[] mask = new int[len];
for(int i=0;i<len;i++) {
for(int j=0;j<words[i].length();j++) {
mask[i] |= 1 << (words[i].charAt(j)-'a');
}
}
int max = 0;
for(int i=0;i<len;i++) {
for(int j=i+1;j<len;j++) {
if((mask[i] & mask[j]) == 0) {
max = Math.max(max, words[i].length() * words[j].length());
}
}
}
return max;
}
相关文章推荐
- 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 题解