Maximum Product of Word Lengths

时间:2022-04-08 17:44:00

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.

分析:

怎么判断两个string没有共同的letter。 我们可以用int的每一个位来表示是否某一个letter出现在某一个字符串中。如果两个字符串的int值AND以后为0,很明显,它们是没有公共letter.

 public class Solution {
public int maxProduct(String[] words) {
if (words == null || words.length <= ) return ; int[] wordInfo = new int[words.length];
for (int i = ; i < words.length; i++) {
for (int j = ; j < words[i].length(); j++) {
// each letter is the 1 bit in the number
wordInfo[i] = wordInfo[i] | ( << words[i].charAt(j) - 'a');
}
}
int maxProduct = ;
for (int i = ; i < words.length; i++) {
for (int j = i + ; j < words.length; j++) {
if (((wordInfo[i] & wordInfo[j]) == )) {
maxProduct = Math.max(maxProduct, words[i].length() * words[j].length());
}
}
} return maxProduct;
}
}