|
| 1 | +class Trie { |
| 2 | + |
| 3 | + private Node head; |
| 4 | + |
| 5 | + public Trie() { |
| 6 | + this.head = new Node('-'); |
| 7 | + } |
| 8 | + |
| 9 | + public void insert(String word) { |
| 10 | + Node curr = this.head; |
| 11 | + for (char c : word.toCharArray()) { |
| 12 | + if (!curr.children.containsKey(c)) { |
| 13 | + curr.children.put(c, new Node(c)); |
| 14 | + } |
| 15 | + curr = curr.children.get(c); |
| 16 | + } |
| 17 | + curr.wordToFrequency.put(word, curr.wordToFrequency.getOrDefault(word, 0) + 1); |
| 18 | + } |
| 19 | + |
| 20 | + public int countWordsEqualTo(String word) { |
| 21 | + Node curr = this.head; |
| 22 | + curr = traverseTrie(curr, word); |
| 23 | + if (curr == null) { |
| 24 | + return 0; |
| 25 | + } |
| 26 | + return curr.wordToFrequency.getOrDefault(word, 0); |
| 27 | + } |
| 28 | + |
| 29 | + public int countWordsStartingWith(String prefix) { |
| 30 | + Node curr = this.head; |
| 31 | + curr = traverseTrie(curr, prefix); |
| 32 | + if (curr == null) { |
| 33 | + return 0; |
| 34 | + } |
| 35 | + int count = 0; |
| 36 | + Queue<Node> queue = new LinkedList<>(); |
| 37 | + queue.add(curr); |
| 38 | + while (!queue.isEmpty()) { |
| 39 | + Node removed = queue.remove(); |
| 40 | + for (String word : removed.wordToFrequency.keySet()) { |
| 41 | + count += removed.wordToFrequency.get(word); |
| 42 | + } |
| 43 | + for (Character child : removed.children.keySet()) { |
| 44 | + queue.add(removed.children.get(child)); |
| 45 | + } |
| 46 | + } |
| 47 | + return count; |
| 48 | + } |
| 49 | + |
| 50 | + public void erase(String word) { |
| 51 | + Node curr = this.head; |
| 52 | + curr = traverseTrie(curr, word); |
| 53 | + if (curr == null || curr.wordToFrequency.getOrDefault(word, 0) == 0) { |
| 54 | + return; |
| 55 | + } |
| 56 | + curr.wordToFrequency.put(word, curr.wordToFrequency.get(word) - 1); |
| 57 | + } |
| 58 | + |
| 59 | + private Node traverseTrie(Node curr, String word) { |
| 60 | + for (char c : word.toCharArray()) { |
| 61 | + if (!curr.children.containsKey(c)) { |
| 62 | + return null; |
| 63 | + } |
| 64 | + curr = curr.children.get(c); |
| 65 | + } |
| 66 | + return curr; |
| 67 | + } |
| 68 | + |
| 69 | + private static class Node { |
| 70 | + char c; |
| 71 | + Map<Character, Node> children; |
| 72 | + Map<String, Integer> wordToFrequency; |
| 73 | + |
| 74 | + public Node(char c) { |
| 75 | + this.c = c; |
| 76 | + this.children = new HashMap<>(); |
| 77 | + this.wordToFrequency = new HashMap<>(); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +/** |
| 83 | + * Your Trie object will be instantiated and called as such: |
| 84 | + * Trie obj = new Trie(); |
| 85 | + * obj.insert(word); |
| 86 | + * int param_2 = obj.countWordsEqualTo(word); |
| 87 | + * int param_3 = obj.countWordsStartingWith(prefix); |
| 88 | + * obj.erase(word); |
| 89 | + */ |
0 commit comments