题目链接


class Solution {
public:
map<int,int>p,cnt;
int groups,maxv;
int find(int x)
{
if(p[x]!=x)p[x]=find(p[x]);
return p[x];
}
void merge(int x,int y)
{
if(!p.count(y))return ;
x=find(x);
y=find(y);
if(x==y)return ;
p[x]=y;
cnt[y]+=cnt[x];
maxv=max(maxv,cnt[y]);
groups--;
}
vector<int> groupStrings(vector<string>& words) {
groups=words.size(),maxv=0;
for(auto word : words)
{
int x=0;
for(auto c : word)
{
x|=1<<(c-'a');
}
p[x]=x;
cnt[x]++;
maxv=max(maxv,cnt[x]);
if(cnt[x]>1)groups--;
}
for(auto &[x,c] : p)
{
for(int i=0;i<26;i++)
{
merge(x,x^(1<<i));
if((x>>i)&1)
{
for(int j=0;j<26;j++)
{
if(((x>>j)&1)==0)
{
merge(x,x^(1<<i)|(1<<j));
}
}
}
}
}
return {groups,maxv};
}
};
本文介绍了一个名为Solution的类,用于处理字符串分组和计算每个组的最大频率。通过find和merge方法,它能将相似的字符串归并到一起,并返回组的数量和最大频率。主要涉及了哈希集合和路径压缩技术。
1463

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



