码迷,mamicode.com
首页 > 其他好文 > 详细

318. Maximum Product of Word Lengths

时间:2017-10-25 13:07:03      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:bsp   imu   turn   rds   case   字母   sum   char   length   

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     }

 

318. Maximum Product of Word Lengths

标签:bsp   imu   turn   rds   case   字母   sum   char   length   

原文地址:http://www.cnblogs.com/wzj4858/p/7728126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!