fork download
  1. import java.util.HashMap;
  2. import java.util.HashSet;
  3. import java.util.Iterator;
  4. import java.util.Map;
  5. import java.util.List;
  6. import java.util.ArrayList;
  7.  
  8.  
  9. /**
  10.  * Class represents trie
  11.  */
  12. class TrieNode
  13. {
  14. boolean isLeaf = false; // set when node is a leaf node
  15. Map<String, TrieNode> children = new HashMap<>();
  16.  
  17. public void insert(String str) {
  18. if (str != null && !str.isEmpty()) {
  19. String[] strSeq = str.split("[\\s]+");
  20.  
  21. // start from current node
  22. TrieNode curr = this;
  23.  
  24. for (int i = 0; i < strSeq.length; i++)
  25. {
  26. // create a new node if path doesn't exists
  27. if (!curr.children.containsKey(strSeq[i])) {
  28. curr.children.put(strSeq[i], new TrieNode());
  29. }
  30. // go to next node
  31. curr = curr.children.get(strSeq[i]);
  32. }
  33.  
  34. curr.isLeaf = true;
  35. }
  36. }
  37.  
  38. public HashSet<TrieNode> getChildrenTrieNodes() {
  39. HashSet<TrieNode> res = new HashSet<>();
  40. for (String c: children.keySet()) {
  41. res.add(children.get(c));
  42. }
  43. return res;
  44. }
  45.  
  46. public void printTrie() {
  47. printTrieWithParams(this,0);
  48. }
  49.  
  50. private void printTrieWithParams(TrieNode node, int offset) {
  51. offset += 1;
  52.  
  53. for (TrieNode tn:node.getChildrenTrieNodes()) {
  54. Iterator<Map.Entry<String, TrieNode>> it = node.children.entrySet().iterator();
  55. if (it.hasNext()) {
  56.  
  57. Map.Entry<String, TrieNode> entry = it.next();
  58.  
  59. for (int i = 0; i < offset; i++) {
  60. System.out.print(" ");
  61. }
  62.  
  63. System.out.println(entry.getKey());
  64.  
  65. if(node.isLeaf) {
  66. System.out.println();
  67. }
  68.  
  69. node = entry.getValue();
  70. printTrieWithParams(node,offset);
  71. }
  72. }
  73. }
  74.  
  75. }
  76.  
  77. public class Main {
  78. public static void main(String[] args) {
  79. TrieNode trie = new TrieNode();
  80. List<String> inputs = new ArrayList<>();
  81.  
  82. String input_0 = "abcd";
  83. String input_1 = "abcd abcd";
  84. String input_2 = "1 2 3 STRING HERE";
  85.  
  86. inputs.add(input_0);
  87. inputs.add(input_1);
  88. inputs.add(input_2);
  89.  
  90.  
  91. for (String s : inputs) {
  92. trie.insert(s);
  93. }
  94.  
  95. trie.printTrie();
  96. }
  97. }
Success #stdin #stdout 0.06s 2184192KB
stdin
Standard input is empty
stdout
 1
  2
   3
    STRING
     HERE
 2
  3
   STRING
    HERE