Leetcode318. 最大单词长度乘积
思路:位运算
如何判断不同单词字母重复?题目的提示是只用小写字母,保证所有的字母最多只有26个,使用 i n t int int前26位保存每一个字母是否出现过,使用 h a s h hash hash存所有单词对应的特征,两次循环遍历哈希表
class Solution {
public:
int maxProduct(vector<string>& words) {
int n = words.size();
unordered_map<int, string> hash;
for (auto& str : words) {
int m = str.size(), t = 0;
for (auto& c : str) {
int u = c - 'a';
t |= (1 << u);
}
if (!hash.count(t) || hash[t].size() < m) hash[t] = str;
}
int res = 0;
for (auto& [n, str1] : hash)
for (auto &[m, str2]: hash)
if ((n & m) == 0) {
int x = str1.size() * str2.size();
if (x > res) {
res = x;
}
}
return res;
}
};