标签:
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.
1 public class Solution { 2 public int maxProduct(String[] words) { 3 if (words == null || words.length <= 1) return 0; 4 5 int[] wordInfo = new int[words.length]; 6 for (int i = 0; i < words.length; i++) { 7 for (int j = 0; j < words[i].length(); j++) { 8 // each letter is the 1 bit in the number 9 wordInfo[i] = wordInfo[i] | (1 << words[i].charAt(j) - ‘a‘); 10 } 11 } 12 int maxProduct = 0; 13 for (int i = 0; i < words.length; i++) { 14 for (int j = i + 1; j < words.length; j++) { 15 if (((wordInfo[i] & wordInfo[j]) == 0)) { 16 maxProduct = Math.max(maxProduct, words[i].length() * words[j].length()); 17 } 18 } 19 } 20 21 return maxProduct; 22 } 23 }
Maximum Product of Word Lengths
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5735167.html