|
| 1 | +package org.ds_algo; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.Map.Entry; |
| 6 | +import java.util.Set; |
| 7 | + |
| 8 | +public class BasicTRIE { |
| 9 | + |
| 10 | + public static void main(String[] args) { |
| 11 | + Node head = new Node(); |
| 12 | + head.ch = null; |
| 13 | + |
| 14 | + addString("hacker", head); |
| 15 | + addString("hack", head); |
| 16 | + addString("hacking", head); |
| 17 | + addString("hacked", head); |
| 18 | + |
| 19 | + addString("animal", head); |
| 20 | + addString("anagram", head); |
| 21 | + addString("angry", head); |
| 22 | + addString("antelope", head); |
| 23 | + addString("anagrams", head); |
| 24 | + |
| 25 | + System.out.println(findInTRIE("hack", head)); |
| 26 | + } |
| 27 | + |
| 28 | + private static int findInTRIE(String str, Node head) { |
| 29 | + Node n = head; |
| 30 | + for (int i = 0; i < str.length(); i++) { |
| 31 | + if (n.children.get(str.charAt(i)) == null) { |
| 32 | + return 0; |
| 33 | + } |
| 34 | + n = n.children.get(str.charAt(i)); |
| 35 | + } |
| 36 | + return n.count; |
| 37 | + } |
| 38 | + |
| 39 | + private static void printTRIE(Node head, int level) { |
| 40 | + for (int i = 0; i < level; i++) { |
| 41 | + System.out.print(" "); |
| 42 | + } |
| 43 | + System.out.println(head.ch); |
| 44 | + Set<Entry<Character, Node>> entries = head.children.entrySet(); |
| 45 | + for (Entry<Character, Node> entry : entries) { |
| 46 | + printTRIE(entry.getValue(), level + 1); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + public static void addString(String str, Node head) { |
| 51 | + Node n = head; |
| 52 | + for (int i = 0; i < str.length(); i++) { |
| 53 | + n = add(str.charAt(i), n); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + public static Node add(char ch, Node head) { |
| 58 | + Node n = head.children.get(ch); |
| 59 | + if (n == null) { |
| 60 | + n = new Node(); |
| 61 | + n.ch = ch; |
| 62 | + head.children.put(ch, n); |
| 63 | + } |
| 64 | + n.count++; |
| 65 | + return n; |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +class Node { |
| 70 | + Character ch; |
| 71 | + Integer count = 0; |
| 72 | + Map<Character, Node> children = new HashMap<>(); |
| 73 | +} |
0 commit comments