题目描述
Given a string array words
, return the maximum value of length(word[i]) * length(word[j])
where the two words do not share common letters. If no such two words exist, return 0
.
Example 1:
Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"] Output: 16 Explanation: The two words can be "abcw", "xtfn".
Example 2:
Input: words = ["a","ab","abc","d","cd","bcd","abcd"] Output: 4 Explanation: The two words can be "ab", "cd".
Example 3:
Input: words = ["a","aa","aaa","aaaa"] Output: 0 Explanation: No such pair of words.
Constraints:
2 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i]
consists only of lowercase English letters.
解题思路
【C++】
class Solution {
public:
int maxProduct(vector<string>& words) {
unordered_map<int, int> hash;
int ans = 0;
for (const string & word : words) {
int mask = 0, size = word.size();
for (const char & c : word) {
mask |= 1 << (c - 'a');
}
hash[mask] = max(hash[mask], size);
for (const auto& [h_mask, h_len]: hash) {
if (!(mask & h_mask)) {
ans = max(ans, size * h_len);
}
}
}
return ans;
}
};
【Java】
class Solution {
int[][] freq;
public int maxProduct(String[] words) {
int len = words.length;
freq = new int[len][26];
for(int i=0;i<len;i++){
char arr[]=words[i].toCharArray();
for(int j=0;j<arr.length;j++){
freq[i][arr[j]-'a']++;
}
}
int max=0;
for(int i=0;i<len-1;i++){
int len_i=words[i].length();
for(int j=i+1;j<len;j++){
if(isOkay(i,j))
max=Math.max(max,len_i*words[j].length());
}
}
return max;
}
boolean isOkay(int i,int j){
for(int k=0;k<26;k++){
if(freq[i][k]>=1 && freq[j][k]>=1)
return false;
}
return true;
}
}