基本思路:可以用一个哈希表来存储字母的情况,一共26个字母,我们可以用二级制表示字母的状态,0表示不存在,1表示存在然后将字母的状态和字母长度储存进哈希表,注意坑点,如果哈希表的字母状态相同需要比较字母长度进行更新,将字母数组处理好之后进行遍历
class Solution {
public:
int maxProduct(vector<string>& words) {
int m = words.size();
unordered_map<int, int> bitMaskMap;
for (int i = 0; i < m; i++) {
int bitMask = 0;
for (char c : words[i]) {
bitMask |= 1 << (c - 'a');
}
if (bitMaskMap.count(bitMask)) {
int maxV = max(bitMaskMap[bitMask], (int)words[i].size());
bitMaskMap[bitMask] = maxV;
} else {
bitMaskMap[bitMask] = words[i].size();
}
}
int ans = 0;
for (auto& x : bitMaskMap) {
for (auto& y : bitMaskMap) {
if ((x.first & y.first) == 0) {
ans = max(ans, x.second * y.second);
}
}
}
return ans;
}
};