318. Maximum Product of Word Lengths
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.
这个问题我们第一反应,应该是使用 set 或者 map 来确认每个词之间没有重复的字母,可以想到,这个方法无疑是很慢的,考虑到每个字符都要做一次比较,其复杂度比 n^2更多。
这道题目同时也给了我们一个很好的提示:字符问题可以用 bit manipulate 来解决的。
因为 int 总共32位,所以完全可以容纳26个字符。我们将比较字符串变成了比较整数。
public class Solution {
public int maxProduct(String[] words) {
if(words == null || words.length == 0){
return 0;
}
int dist = Integer.MIN_VALUE;
int[] bit = new int[words.length];
for(int i = 0; i < words.length; i++){
for(int j = 0; j<words[i].length(); j++){
bit[i] |= 1<<(words[i].charAt(j) -'a');
}
}
for(int i = 0; i< words.length -1; i++){
for(int j = i + 1; j<words.length;j++){
if((bit[i] & bit[j]) == 0 ){
dist = Math.max(words[i].length() * words[j].length(),dist);
}
}
}
return dist == Integer.MIN_VALUE? 0:dist;
}
}