剑指 Offer II 005. 单词长度的最大乘积
思路:1. 首先本题最简单的方法是双层循环判断每俩个单词是否有共同字符,接着算乘积。
而判断是否有共同字符又需要双层循环,所以很容易想到将判断共同字符的时间复杂度降低。
2. 由于是字符串的判断,所以直接使用哈希表判断的话,需要构建n个哈希表。
3. 因此我们将26个字母看成26个比特位,如果此字符串包含某个字母,则将这个比特位置为1。
4. 我们先将每个字符串通过这个方法转化为数字,保存到哈希表中,在进行判断。
5. 求最大长度的乘积,所以包含相同字母的字符串可以直接使用长度最大的那个保存到哈希表中。
class Solution {
public:
int maxProduct(vector<string>& words) {
unordered_map<int,int> occ;
int res = 0;
for(int i = 0;i < words.size();i++)
{
int temp = 0;
for(auto e : words[i])
{
int x = e - 'a' + 1;//将字母转化为第x个比特位
temp |= (1 << x);//比特位置一
}
int x = words[i].length();
if(!occ.count(temp) || occ[temp] < x)//保留长度最大的那个
occ[temp] = x;
}
for(auto e : occ)
{
for(auto t : occ)
{
if((e.first & t.first) == 0)
{
int x = e.second * t.second;
res = max(res,x);
}
}
}
return res;
}
};