题目描述:
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.
(在一个字符串组成的数组words中,找出max{Length(words[i]) * Length(words[j])},其中words[i]和words[j]中没有相同的字母,在这里字符串由小写字母a-z组成的。如果没有这两个词存在,返回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.
思路:用26个二进制位来表示字符串,例如a就是0000...0001,ac就是0000....0101,xyz就是1110...0000,如何判断两个字符串有没有相同的字母就是用两个二进制数相与例如 ac(0101)和bd(1010)相与为0,那么这两个字符串没有相同的字母,如果ac(0101)和bc(0110)相与得4(0100),不为0,那么就由相同的字母。
public class Maximum_Product_of_Word_Lengths {
//将一个字符串表示为一个二进制数
public static int TransformNum(String word)
{
int num = 0;
for(int i=0;i<word.length();i++)
{
int mid = 1;
int diff = word.charAt(i)-97;
while(diff>0)
{
mid <<= 1;
diff--;
}
num |= mid;
}
return num;
}
public static int maxProduct(String[] words)
{
int num[] = new int[words.length];
for(int i=0;i<words.length;i++)
{
num[i] = TransformNum(words[i]);
}
int result = 0;
for(int i=1;i<words.length;i++)
{
for(int j=0;j<i;j++)
{
if((num[i]&num[j])==0)
{
result = Math.max(result,words[i].length()*words[j].length());
}
}
}
return result;
}
public static void main(String[] args) {
String words[] = {"a", "ab", "abc", "d", "cd", "bcd", "abcd"};
System.out.println(maxProduct(words));
}
}