问题:
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.
解决:
【题意】给出一个字符串数组,找出数组中两个单词长度相乘最大的乘积,并且这两个单词不能有相同的字母。要满足的条件:(1)两个单词不能有相同的字母;(2)长度相乘最大;
① 暴力破解,O(N^2)。超时
class Solution {
public int maxProduct(String[] words) {
int res = 0;
int len1 = 0;
int len2 = 0;
Arrays.sort(words, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
for (int i = words.length - 1;i >= 1;i --){
for (int j = i - 1;j >= 0;j --){
if (hasCommon(words[i],words[j])){
continue;
}else{
len1 = words[i].length();
len2 = words[j].length();
res = Math.max(res,len1 * len2);
}
}
}
return res;
}
public boolean hasCommon(String s1,String s2){
if (s1 == "" || s1.length() == 0) return false;
if (s2.indexOf(s1) != -1){
return true;
}else{
return hasCommon(s1.substring(0,s1.length() - 1),s2) || hasCommon(s1.substring(1),s2);
}
}
}
② 使用mask,一个整型数int有32位,我们可以用后26位来对应26个小写字母,若为1,说明该对应位置的字母出现过,那么每个单词的都可由一个int数字表示,两个单词没有共同字母的条件是这两个int数相与为0。
class Solution { //36ms
public int maxProduct(String[] words) {
int res = 0;
int[] mask = new int[words.length];
for (int i = 0;i < words.length;i ++){
for (char c : words[i].toCharArray()){//对词组进行编码
mask[i] = mask[i] | 1 << (c - 'a');
}
for (int j = 0;j < i;j ++){
if ((mask[i] & mask[j]) == 0){//两词组没有重复的部分
int len1 = words[i].length();
int len2 = words[j].length();
res = Math.max(res,len1 * len2);
}
}
}
return res;
}
}
③ 在discuss中看到的。增加一个数组记录对应单词的长度。
class Solution { //24ms
public int maxProduct(String[] words) {
int[] mask = new int[words.length];//用于存储字符是否出现
int[] lens = new int[words.length];//用于保存对应词组的长度
for (int i = 0;i < words.length;i ++){
int tmp = 0;//保存每个词组编码后的值
for (char c : words[i].toCharArray()){
tmp = tmp | 1 << (c - 'a');
}
mask[i] = tmp;
lens[i] = words[i].length();
}
int res = 0;
for (int i = 0;i < mask.length;i ++){
for (int j = i + 1;j < mask.length;j ++){
if ((mask[i] & mask[j]) == 0){
res = Math.max(res,lens[i] * lens[j]);
}
}
}
return res;
}
}