|
| 1 | +class Solution { |
| 2 | + public List<List<String>> deleteDuplicateFolder(List<List<String>> paths) { |
| 3 | + TrieNode root = new TrieNode(); |
| 4 | + for (List<String> path : paths) { |
| 5 | + TrieNode node = root; |
| 6 | + for (String dir : path) { |
| 7 | + if (!node.children.containsKey(dir)) { |
| 8 | + node.children.put(dir, new TrieNode()); |
| 9 | + } |
| 10 | + node = node.children.get(dir); |
| 11 | + } |
| 12 | + } |
| 13 | + Map<String, Integer> frequencyMap = new HashMap<>(); |
| 14 | + construct(root, frequencyMap); |
| 15 | + List<List<String>> result = new ArrayList<>(); |
| 16 | + List<String> path = new ArrayList<>(); |
| 17 | + operate(root, frequencyMap, result, path); |
| 18 | + return result; |
| 19 | + } |
| 20 | + |
| 21 | + private void construct(TrieNode root, Map<String, Integer> frequencyMap) { |
| 22 | + if (root.children.isEmpty()) { |
| 23 | + return; |
| 24 | + } |
| 25 | + List<String> serialized = new ArrayList<>(); |
| 26 | + for (Map.Entry<String, TrieNode> entry : root.children.entrySet()) { |
| 27 | + construct(entry.getValue(), frequencyMap); |
| 28 | + serialized.add(entry.getKey() + "(" + entry.getValue().serialized + ")"); |
| 29 | + } |
| 30 | + serialized.sort(String::compareTo); |
| 31 | + StringBuilder sb = new StringBuilder(); |
| 32 | + for (String s : serialized) { |
| 33 | + sb.append(s); |
| 34 | + } |
| 35 | + root.serialized = sb.toString(); |
| 36 | + frequencyMap.put(root.serialized, frequencyMap.getOrDefault(root.serialized, 0) + 1); |
| 37 | + } |
| 38 | + |
| 39 | + private void operate(TrieNode root, Map<String, Integer> frequencyMap, List<List<String>> result, List<String> path) { |
| 40 | + if (frequencyMap.getOrDefault(root.serialized, 0) > 1) { |
| 41 | + return; |
| 42 | + } |
| 43 | + if (!path.isEmpty()) { |
| 44 | + result.add(new ArrayList<>(path)); |
| 45 | + } |
| 46 | + for (Map.Entry<String, TrieNode> entry : root.children.entrySet()) { |
| 47 | + path.add(entry.getKey()); |
| 48 | + operate(entry.getValue(), frequencyMap, result, path); |
| 49 | + path.removeLast(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + static class TrieNode { |
| 54 | + final Map<String, TrieNode> children; |
| 55 | + String serialized; |
| 56 | + |
| 57 | + public TrieNode() { |
| 58 | + children = new HashMap<>(); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments