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 @   daniel456  阅读(93)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示