解题思路
两两对比字符串,记录所有符合条件的字符串组的乘积最大值
提交代码
class Solution {
public int maxProduct(String[] words) {
int res=0,tmp=0;
for(int i=0;i<words.length;i++) {
for(int j=i+1;j<words.length;j++) {
tmp=words[i].length()*words[j].length();
if(tmp<res) continue;
if(!hasCommon(words[i],words[j]))
res=tmp;
}
}
return res;
}
private boolean hasCommon(String s1,String s2) {
Map<Character,Integer> map1=new HashMap<>();
Map<Character,Integer> map2=new HashMap<>();
for(int i=0;i<s1.length();i++) {
if(!map1.containsKey(s1.charAt(i)))
map1.put(s1.charAt(i),1);
}
for(int i=0;i<s2.length();i++) {
if(!map2.containsKey(s2.charAt(i)))
map2.put(s2.charAt(i),1);
}
for(Character key : map1.keySet()) {
if(map2.containsKey(key))
return true;
}
return false;
}
}
运行结果:
优化后的代码
class Solution{
public int maxProduct(String[] words) {
if (words == null || words.length == 0) return 0;
int len=words.length;
int[] charSet = new int[len];
for (int i = 0; i < len; i++) {
String word = words[i];
for(char c : word.toCharArray())
charSet[i]|=1<<(c-'a');
}
int res = 0;
for (int i = 0; i < len; i++)
for (int j = i + 1; j < len; j++) {
if ((charSet[i] & charSet[j]) == 0 && (words[i].length() * words[j].length() > res))
res = words[i].length() * words[j].length();
}
return res;
}
}