Leetcode318. 最大单词长度乘积
思路:位运算
如何判断不同单词字母重复?题目的提示是只用小写字母,保证所有的字母最多只有26个,使用intintint前26位保存每一个字母是否出现过,使用hashhashhash存所有单词对应的特征,两次循环遍历哈希表
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;
}
};
LeetCode 318题解
本文介绍了一种利用位运算解决LeetCode 318题“最大单词长度乘积”的方法。通过使用int类型变量记录每个单词中出现的小写字母,并存储于哈希表中,最终通过两层循环找出不包含相同字母的两个最长单词,计算并返回它们长度的乘积。

被折叠的 条评论
为什么被折叠?



