-
Notifications
You must be signed in to change notification settings - Fork 1
/
NameAndEmail.java
53 lines (48 loc) · 2 KB
/
NameAndEmail.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
44
45
46
47
48
49
50
51
52
53
import java.util.*;
public class NameAndEmail {
public static void main(String[] args) {
List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("John", "johnsmith@mail.com", "john_newyork@mail.com"));
list.add(Arrays.asList("John","johnsmith@mail.com","john00@mail.com"));
list.add(Arrays.asList("Mary","mary@mail.com"));
System.out.println(accountsMerge(list).toString());
}
public static List<List<String>> accountsMerge(List<List<String>> accounts) {
Map<String, Set<String>> graph = new HashMap<>(); //<email node, neighbor nodes>
Map<String, String> name = new HashMap<>(); //<email, username>
// Build the graph;
for (List<String> account : accounts) {
String userName = account.get(0);
for (int i = 1; i < account.size(); i++) {
if (!graph.containsKey(account.get(i))) {
graph.put(account.get(i), new HashSet<>());
}
name.put(account.get(i), userName);
if (i == 1) continue;
graph.get(account.get(i)).add(account.get(i - 1));
graph.get(account.get(i - 1)).add(account.get(i));
}
}
Set<String> visited = new HashSet<>();
List<List<String>> res = new LinkedList<>();
// DFS search the graph;
for (String email : name.keySet()) {
List<String> list = new LinkedList<>();
if (visited.add(email)) {
dfs(graph, email, visited, list);
Collections.sort(list);
list.add(0, name.get(email));
res.add(list);
}
}
return res;
}
public static void dfs(Map<String, Set<String>> graph, String email, Set<String> visited, List<String> list) {
list.add(email);
for (String next : graph.get(email)) {
if (visited.add(next)) {
dfs(graph, next, visited, list);
}
}
}
}