[leetcode]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:

Input: ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16 
Explanation: The two words can be "abcw", "xtfn".

Example 2:

Input: ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4 
Explanation: The two words can be "ab", "cd".

题意:

给定一堆单词,要求找出俩单词长度的最大乘积,要求俩单词不能有相同字母。

思路:

判断noOverLapping: 用2个set分别标记俩单词, 扫一遍set,若发现某个字母被同时标记过,则有重叠。

取最大乘积长度:两重for循环,两两比较,更新最大值。

代码:

 1 class Solution {
 2     public int maxProduct(String[] words) {
 3         int result = 0;
 4         for (int i = 0; i < words.length; ++i) {
 5             for (int j = i + 1; j < words.length; ++j) {
 6                 int tmp = words[i].length() * words[j].length();
 7                 if ( noOverLapping(words[i], words[j])&& tmp > result) {
 8                     result = tmp;
 9                 }
10             }
11         }
12         return result;       
13 }   
14     private boolean noOverLapping(String a , String b){
15         boolean[] setA = new boolean[256];
16         boolean[] setB = new boolean[256];
17         
18         for(int i = 0; i < a.length(); i++){
19             setA[a.charAt(i)] = true;
20         }
21         
22         for(int i = 0; i < b.length(); i++){
23             setB[b.charAt(i)] = true;
24         }
25         
26         for(int i = 0; i < 256; i++){
27             if(setA[i] == true && setB[i] == true){
28                 return false;
29             }
30         }
31         
32         return true;
33     }   
34 }

可以进一步优化:对于如何判断俩单词有没有相同字母,可用位向量表示每个字母是否出现即可,俩位向量异或即可得出是否有相同字母。

 1 public class Solution {
 2     public int maxProduct(String[] words) {
 3         final int n = words.length;
 4         final int[] hashset = new int[n];
 5 
 6         for (int i = 0; i < n; ++i) {
 7             for (int j = 0; j < words[i].length(); ++j) {
 8                 hashset[i] |= 1 << (words[i].charAt(j) - 'a');
 9             }
10         }
11 
12         int result = 0;
13         for (int i = 0; i < n; ++i) {
14             for (int j = i + 1; j < n; ++j) {
15                 int tmp = words[i].length() * words[j].length();
16                 if ((hashset[i] & hashset[j]) == 0 && tmp > result) {
17                     result = tmp;
18                 }
19             }
20         }
21         return result;
22     }
23 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9158260.html