318. Maximum Product of Word Lengths

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.

含义:扎到两个子串,使得他们长度的乘积最大,要求是一个子串的字符不能在另外一个子串中出现

 1     public int maxProduct(String[] words) {
 2 //        http://blog.csdn.net/li563868273/article/details/51581224
 3 //        我们把每个字符串数组看成一个26大小的数组,小写字母a-z是26位,“abcd” 的int值为 0000 0000 0000 0000 0000 0000 0000 1111,
 4 //        “wxyz” 的int值为 1111 0000 0000 0000 0000 0000 0000 0000,这样两个进行与(&)得到0, 如果有相同的字母则不是0。
 5         int len=words.length;
 6         if (len<=1) return 0;
 7         int[] mask=new int[len];
 8         //abcd可以length=4
 9         //words[i].charAt(0) 0左移0位
10         for (int i = 0; i < len; i++) {
11             for (int j = 0; j <words[i].length() ; j++) {
12                 mask[i] |= 1<<(words[i].charAt(j)-'a');
13             }
14         }
15         int max= 0;
16         for (int i = 0; i < len; i++) {
17             for (int j = i+1; j <len ; j++) {
18                 if((mask[i] & mask[j]) == 0){
19                     max=Math.max(max,words[i].length()*words[j].length());
20                 }
21             }
22         }
23         return max;        
24     }

 

posted @ 2017-10-25 11:55  daniel456  阅读(91)  评论(0编辑  收藏  举报