-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathSimilar String Groups.java
More file actions
51 lines (49 loc) · 1.55 KB
/
Similar String Groups.java
File metadata and controls
51 lines (49 loc) · 1.55 KB
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
class Solution {
public int numSimilarGroups(String[] strs) {
int n = strs.length;
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (isSimilar(strs[i], strs[j])) {
graph.computeIfAbsent(i, k -> new ArrayList<>()).add(j);
graph.computeIfAbsent(j, k -> new ArrayList<>()).add(i);
}
}
}
boolean[] visited = new boolean[n];
int count = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
bfs(i, graph, visited);
count++;
}
}
return count;
}
private boolean isSimilar(String s1, String s2) {
int diff = 0;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
diff++;
}
}
return diff == 0 || diff == 2;
}
private void bfs(int node, Map<Integer, List<Integer>> graph, boolean[] visited) {
Queue<Integer> queue = new LinkedList<>();
queue.add(node);
visited[node] = true;
while (!queue.isEmpty()) {
node = queue.poll();
if (!graph.containsKey(node)) {
continue;
}
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
}