Maximum Product of Word

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Maximum Product of Word相关的知识,希望对你有一定的参考价值。

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.

 

Analyse: As seeing this problem, I first think of brute force. For each word in the array, find other words don‘t share common words with it. Time exceeded. 

 1 class Solution {
 2 public:
 3     int maxProduct(vector<string>& words) {
 4         int result = 0;
 5         if(words.size() < 2) return result;
 6         
 7         for(int i = 0; i < words.size(); i++){
 8             for(int j = i + 1; j < words.size(); j++){
 9                 if(!hasCommon(words[i], words[j])){
10                     int temp = (words[i].length()) * (words[j].length());
11                     result = max(result, temp);
12                 }
13             }
14         }
15         return result;
16     }
17     
18     bool hasCommon(string s1, string s2){
19         if(s1.empty() || s2.empty()) return false;
20         
21         for(int i = 0; i < s1.length(); i++){
22             for(int j = 0; j < s2.length(); j++){
23                 if(s2[j] == s1[i])
24                     return true;
25             }
26         }
27         return false;
28     }
29 };

 Of course it will exceed time limit because the time complexity is O(n^4)....

 

Below I‘ll give a O(n^2) solution. 

 1 class Solution {
 2 public:
 3     int maxProduct(vector<string>& words) {
 4         if(words.size() < 2) return 0;
 5         
 6         int result = 0;
 7         vector<int> bits(words.size(), 0);
 8         for(int i = 0; i < words.size(); i++){
 9             for(int j = 0; j < words[i].size(); j++)
10                 bits[i] |= 1 << (words[i][j] - a);
11         }
12         
13         for(int i = 0; i < words.size(); i++){
14             for(int j = i; j < words.size(); j++){
15                 if(!(bits[j] & bits[i])){
16                     int temp = words[i].length() * words[j].length(); 
17                     result = max(result, temp);
18                 }
19             }
20         }
21         return result;
22     }
23 };

 

以上是关于Maximum Product of Word的主要内容,如果未能解决你的问题,请参考以下文章

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths