1
// OJ: https://leetcode.com/problems/groups-of-strings/2
// Author: github.com/lzl124631x3
// Time: O(26 * N * alpha(N))6
vector<int> id, rank, size;10
UnionFind(int n) : id(n), rank(n, 0), size(n, 1), cnt(n) {11
iota(begin(id), end(id), 0);14
return id[a] == a ? a : (id[a] = find(id[a]));16
void connect(int a, int b) {17
int x = find(a), y = find(b);19
if (rank[x] > rank[y]) {25
if (rank[x] == rank[y]) rank[y]++;38
vector<int> groupStrings(vector<string> &A) {41
unordered_map<int, int> m, delMap;43
for (int i = 0; i < N; ++i) {45
for (char c : A[i]) h |= 1 << (c - 'a'); // `h` is the bitmask representation of `A[i]`46
for (int j = 0; j < 26; ++j) {47
if (h >> j & 1) { // if `h`'s j-th bit is 148
int del = h ^ (1 << j); // `del` is the bitmask after deleting the `j`-th bit49
if (m.count(del)) uf.connect(i, m[del]); // Connect `A[i]` with its deletion variant50
if (delMap.count(del))51
uf.connect(i, delMap[del]);55
int add = h | (1 << j); // `add` is the bitmask after adding `j`-th bit56
if (m.count(add)) uf.connect(i, m[add]);62
for (int i = 0; i < N; ++i) mx = max(mx, uf.getSize(i));63
return {uf.getCount(), mx};