题目链接
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};
}
};