题目: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.
翻译:给定一个字符串数组,求两个元素长度的乘积最大值,且这两个元素中不包含相同的字母(字母为a-z)
思路:一般关于字母的题,可以考虑位运算(类似于之前介绍过的统计二进制中“1”的个数),小写字母有26个,一个int有32位,所以可以用一个int表示一个字符串!!!!这是关键思想!!!!eg:"abcd" = 0000 0000 0000 0000 0000 0000 0000 1111
"wxyz" = 0000 0011 1100 0000 0000 0000 0000 0000,所以评判两个字符串是否有公共字母就转变成两个整型数字相与&的操作,若&的结果为0,则证明两个字符串没有公共的字母,若结果不为0,则证明有公共的字母。有了这个思想后,我们便只需开一个int数组,长度等于字符串数组长度即可,每一个int记录一个字符串,遍历一遍字符串数组后,便初始化完成了这个int数组,之后再遍历一遍int数组,对于&之后为0的两个元素进行长度的相乘,从而统计出最大的长度即可!
public class Solution {
public int maxProduct(String[] words) {
int length = words.length;
int[] wordsTonums = new int[length];
String tmp =null;
for(int i=0;i<length;i++){
tmp = words[i];
int size = tmp.length();
for(int j=0;j<size;j++){
wordsTonums[i] |= 1 << (tmp.charAt(j)-'a');
}
}
int result=0;
int max = 0;
for(int i=0;i<length-1;i++){
for(int j=i+1;j<length;j++){
if((wordsTonums[i] & wordsTonums[j]) == 0){
result = words[i].length() * words[j].length();
if(result > max)
max = result;
}
}
}
return max;
}
}