-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
Copy pathSolution.java
43 lines (40 loc) · 975 Bytes
/
Solution.java
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
class Solution {
private int[] p;
public int numSimilarGroups(String[] strs) {
int n = strs.length;
p = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
}
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (check(strs[i], strs[j])) {
p[find(i)] = find(j);
}
}
}
int res = 0;
for (int i = 0; i < n; ++i) {
if (i == find(i)) {
++res;
}
}
return res;
}
private boolean check(String a, String b) {
int cnt = 0;
int n = a.length();
for (int i = 0; i < n; ++i) {
if (a.charAt(i) != b.charAt(i)) {
++cnt;
}
}
return cnt <= 2;
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}