839. Similar String Groups

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution {
private static class UnionFind {

private final int[] parent;
private int count;

public UnionFind(int n) {
this.parent = new int[n];
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
}
this.count = n;
}

public void union(int x, int y) {
int rootX = getRoot(x), rootY = getRoot(y);
if (rootX == rootY) {
return;
}

parent[rootX] = rootY;
count--;
}

private int getRoot(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // path compression
x = parent[x];
}

return x;
}

public boolean isConnected(int x, int y) {
return getRoot(x) == getRoot(y);
}

public int getCount() {
return count;
}
}

public int numSimilarGroups(String[] strs) {
UnionFind unionFind = new UnionFind(strs.length);
for (int i = 0; i < strs.length; i++) {
for (int j = i + 1; j < strs.length; j++) {
if (!unionFind.isConnected(i, j) && isSimilar(strs, i, j)) {
unionFind.union(i, j);
}
}
}

return unionFind.getCount();
}

private boolean isSimilar(String[] strs, int i, int j) {
String strA = strs[i], strB = strs[j];
int diff = 0;
for (int k = 0; k < strA.length(); k++) {
if (strA.charAt(k) != strB.charAt(k)) {
diff++;
}
}

return diff <= 2;
}
}

References

839. Similar String Groups
剑指 Offer II 117. 相似的字符串