|
| 1 | +class Solution { |
| 2 | + public List<List<String>> accountsMerge(List<List<String>> accounts) { |
| 3 | + Map<String, String> emailToName = new HashMap<>(); |
| 4 | + Map<String, List<String>> graph = new HashMap<>(); |
| 5 | + |
| 6 | + for (List<String> account : accounts) { |
| 7 | + String name = account.get(0); |
| 8 | + |
| 9 | + for (int i = 1; i < account.size(); i++) { |
| 10 | + graph.computeIfAbsent(account.get(i), k -> new ArrayList<>()).add(account.get(1)); |
| 11 | + graph.computeIfAbsent(account.get(1), k -> new ArrayList<>()).add(account.get(i)); |
| 12 | + emailToName.put(account.get(i), name); |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + Set<String> visited = new HashSet<>(); |
| 17 | + List<List<String>> mergedAccounts = new ArrayList<>(); |
| 18 | + for (String email : graph.keySet()) { |
| 19 | + if (!visited.contains(email)) { |
| 20 | + visited.add(email); |
| 21 | + Stack<String> stack = new Stack<>(); |
| 22 | + stack.push(email); |
| 23 | + List<String> singleAccount = new ArrayList<>(); |
| 24 | + while (!stack.isEmpty()) { |
| 25 | + String removed = stack.pop(); |
| 26 | + singleAccount.add(removed); |
| 27 | + for (String connected : graph.get(removed)) { |
| 28 | + if (!visited.contains(connected)) { |
| 29 | + visited.add(connected); |
| 30 | + stack.push(connected); |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + Collections.sort(singleAccount); |
| 35 | + singleAccount.add(0, emailToName.get(email)); |
| 36 | + mergedAccounts.add(singleAccount); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return mergedAccounts; |
| 41 | + } |
| 42 | +} |
0 commit comments