0839.cpp (1251B)
1 class UnionFind { 2 int n, cnt = n; 3 vector<int> root, size; 4 5 public: 6 UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } 7 8 int find(int x) { 9 while (x != root[x]) 10 x = root[x] = root[root[x]]; 11 return x; 12 } 13 14 void join(int x, int y) { 15 x = find(x), y = find(y); 16 if (x != y) { 17 if (size[x] > size[y]) swap(x, y); 18 root[x] = y; 19 size[y] += size[x]; 20 cnt--; 21 } 22 } 23 24 int count() { return cnt; } 25 bool connected(int x, int y) { return find(x) == find(y); } 26 }; 27 28 class Solution { 29 bool similar(const string &s1, const string &s2) { 30 int diff = 0; 31 for (int i = 0; i < s1.size(); i++) { 32 if (s1[i] == s2[i]) continue; 33 if (diff < 2) 34 diff++; 35 else 36 return false; 37 } 38 return true; 39 } 40 41 public: 42 int numSimilarGroups(const vector<string> &strs) { 43 int n = strs.size(); 44 UnionFind uf(n); 45 for (int i = 0; i < n; i++) { 46 for (int j = i + 1; j < n; j++) { 47 if (similar(strs[i], strs[j])) uf.join(i, j); 48 } 49 } 50 return uf.count(); 51 } 52 };