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
| class Solution { public List<List<String>> accountsMerge(List<List<String>> accounts) { Map<String, Set<String>> graph = new HashMap<>(); Map<String, String> emailToName = new HashMap<>(); for (List<String> account : accounts) { String name = account.get(0); for (int i = 1; i < account.size(); i++) { graph.computeIfAbsent(account.get(i), k -> new HashSet<>()); emailToName.put(account.get(i), name); 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>> ans = new LinkedList<>(); for (String email : emailToName.keySet()) { List<String> list = new LinkedList<>(); if (visited.add(email)) { dfs(graph, email, visited, list); Collections.sort(list); list.add(0, emailToName.get(email)); ans.add(list); } } return ans; } private 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); } }
|