LeetCode Maximum Product of Word Lengths

原题链接在这里:https://leetcode.com/problems/maximum-product-of-word-lengths/

用mark[i]数组来标记 words[i]都含有哪些字母,假若有个'c', 就在第三位上有个1. 

通过mark[i] & mark[j] 是否为0来确定是否有相同的字母。

排序words是为了能尽量节省一些时间,去掉没有意义的比较。

Time Complexity: O(n^2), n是有多少个string.

Space: O(n), 生成了mark.

AC Java:

 1 public class Solution {
 2     public int maxProduct(String[] words) {
 3         if(words == null || words.length == 0){
 4             return 0;
 5         }
 6         
 7         //排序words, 按照长度大到小, 为了后面节省时间
 8         Arrays.sort(words, new Comparator<String>(){
 9             public int compare(String s1, String s2){
10                 return s2.length() - s1.length();
11             }
12         });
13         
14         int [] mark = new int[words.length];
15         for(int i = 0; i<words.length; i++){
16             for(int j = 0; j<words[i].length(); j++){
17                 mark[i] |= (1 << words[i].charAt(j)-'a');
18             }
19         }
20         
21         int res = 0;
22         for(int i = 0; i<words.length; i++){
23             if(words[i].length() * words[i].length() <= res){
24                 //因为words已经按照长度大到小排序了,若是words[i]长度平方还小于res, 后面的更小
25                 break;
26             }
27             for(int j = i+1; j<words.length; j++){
28                 if((mark[i] & mark[j]) == 0){
29                     res = Math.max(res, words[i].length() * words[j].length());
30                     //后面更小,没有必要继续了
31                     break;
32                 }
33             }
34         }
35         
36         return res;
37     }
38 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5150795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值