publicvoidunion(int x, int y) { introotX= getRoot(x), rootY = getRoot(y); if (rootX == rootY) { return; }
parent[rootX] = rootY; count--; }
privateintgetRoot(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; // path compression x = parent[x]; }
return x; }
publicbooleanisConnected(int x, int y) { return getRoot(x) == getRoot(y); }
publicintgetCount() { return count; } }
publicintnumSimilarGroups(String[] strs) { UnionFindunionFind=newUnionFind(strs.length); for (inti=0; i < strs.length; i++) { for (intj= i + 1; j < strs.length; j++) { if (!unionFind.isConnected(i, j) && isSimilar(strs, i, j)) { unionFind.union(i, j); } } }
return unionFind.getCount(); }
privatebooleanisSimilar(String[] strs, int i, int j) { StringstrA= strs[i], strB = strs[j]; intdiff=0; for (intk=0; k < strA.length(); k++) { if (strA.charAt(k) != strB.charAt(k)) { diff++; } }