题目描述
给定一个字符串数组 words,请计算当两个字符串 words[i] 和 words[j] 不包含相同字符时,它们长度的乘积的最大值。假设字符串中只包含英语的小写字母。如果没有不包含相同字符的一对字符串,返回 0。
提示:
2 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i] 仅包含小写字母
样例
输入: words = ["abcw","baz","foo","bar","fxyz","abcdef"]
输出: 16
解释: 这两个单词为 "abcw", "fxyz"。它们不包含相同字符,且长度的乘积最大。
输入: words = ["a","ab","abc","d","cd","bcd","abcd"]
输出: 4
解释: 这两个单词为 "ab", "cd"。
输入: words = ["a","aa","aaa","aaaa"]
输出: 0
解释: 不存在这样的两个单词。
状态压缩
因为只包含小写字母,可以记录在int位信息中来确认包含关系
如:101 说明包含c,a
如 010 说明包含 b
101 & 010 = 0,即两者之间字母均不同
时间复杂度
O(n^2)
C++ 代码
class Solution {
public:
int maxProduct(vector<string>& words) {
int n = words.size(),maxt = 0;
vector<int> aux;
for(auto& w : words) aux.push_back(cal(w));
for(int i = 0; i < n; i ++){
for(int j = i+1; j < n; j ++){
if(aux[i] & aux[j]) continue;
int curt = words[i].size() * words[j].size();
maxt = max(maxt,curt);
}
}
return maxt;
}
int cal(string& s){
int res = 0;
for(auto& x : s)
res |= 1 << (x - 'a');
return res;
}
};