第一版:
class Solution {
public:
int maxProduct(vector<string>& words) {
int num = words.size();
int ans = 0;
for(int i = 0; i < num; i++){
int m = words[i].size();
for(int j = i + 1; j < num; j++){
int n = words[j].size();
if(!has_same_word(words[i], words[j])){
ans = max(ans, m * n);
}
}
}
return ans;
}
bool has_same_word(string str1, string str2){
vector<int> alpha(26, 0);
for(int i = 0; i < str1.size(); i++){
alpha[str1[i] - 'a'] = 1;
}
for(int j = 0; j < str2.size(); j++){
if(alpha[str2[j] - 'a'] == 1){
return true;
}
}
return false;
}
};
第二版:
class Solution {
public:
int maxProduct(vector<string>& words) {
int len = words.size();
vector<int> save(len , 0);
for(int i = 0; i < len; i++){
int maskbit = 0;
for(char c : words[i]){
maskbit |= (1 << (c - 'a'));
}
save[i] = maskbit;
// cout<<save[i]<<endl;
}
int ans = 0;
for(int i = 0; i < len; i++){
int m = words[i].size();
for(int j = i + 1; j < len; j++){
if(!(save[i] & save[j])){
int n = words[j].size();
ans = max(ans, m * n);
// cout<<"m = "<<m<<" , n = "<<n<<endl;
}
}
}
return ans;
}
bool has_same_word(string str1, string str2){
int ans1 = 0, ans2 = 0;
for(int i = 0; i < str1.size(); i++){
ans1 |= 1<<(str1[i] - 'a');
}
for(int j = 0; j < str2.size(); j++){
ans2 |= 1<<(str2[j] - 'a');
}
if(ans1 & ans2)return true;
else return false;
}
};
第三版:
class Solution {
public:
int maxProduct(vector<string>& words) {
int len = words.size();
unordered_map<int, int> mask_map;
for(int i = 0; i < len; i++){
int maskbit = 0;
for(char c : words[i]){
maskbit |= (1 << (c - 'a'));
}
if(mask_map.count(maskbit)){
int max_val = max(mask_map[maskbit], (int)words[i].size()); //把第二个参数转成和第一个参数一样的 int 型,问题得以解决
mask_map[maskbit] = max_val;
}
else{
mask_map[maskbit] = words[i].size();
}
}
int ans = 0;
for(auto x : mask_map){
for(auto y : mask_map){
if((x.first & y.first) == 0)
ans = max(ans, x.second * y.second);
}
}
return ans;
}
bool has_same_word(string str1, string str2){
int ans1 = 0, ans2 = 0;
for(int i = 0; i < str1.size(); i++){
ans1 |= 1<<(str1[i] - 'a');
}
for(int j = 0; j < str2.size(); j++){
ans2 |= 1<<(str2[j] - 'a');
}
if(ans1 & ans2)return true;
else return false;
}
};