-
Notifications
You must be signed in to change notification settings - Fork 65
/
TrieImplementation.java
128 lines (114 loc) · 2.31 KB
/
TrieImplementation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/**
* Data-Structures-In-Java
* TrieImplementation.java
*/
package com.deepak.data.structures.Trie;
import java.util.HashMap;
/**
* Class to hold Trie implementation
* Not making it generic since keys are usually strings
*
* @author Deepak
*/
public class TrieImplementation {
/**
* Root Node
*/
private TrieNode root;
/**
* Default Constructor
*/
public TrieImplementation() {
root = new TrieNode();
}
/**
* Method to insert a word in Trie
*
* @param word
*/
public void insert(String word) {
/* Find the children of root node */
HashMap<Character, TrieNode> children = root.children;
for (int i = 0; i < word.length(); i++) {
char character = word.charAt(i);
TrieNode node = null;
if (children.containsKey(character)) {
node = children.get(character);
} else {
node = new TrieNode(character);
children.put(character, node);
}
children = node.children;
if (i == word.length() - 1) {
node.isLeaf = true;
}
}
}
/**
* Method to check if a word in Trie starts with the given prefix
*
* @param prefix
* @return {@link boolean}
*/
public boolean startsWith(String prefix) {
if (searchNode(prefix) != null) {
return true;
}
return false;
}
/**
* Method to search TrieNode based on the word
*
* @param word
* @return {@link TrieNode}
*/
public TrieNode searchNode(String word) {
HashMap<Character, TrieNode> children = root.children;
TrieNode node = null;
for (int i = 0; i < word.length(); i++) {
char character = word.charAt(i);
if (children.containsKey(character)) {
node = children.get(character);
children = node.children;
} else {
return null;
}
}
return node;
}
/**
* Method to search the given word in the Trie
*
* @param word
* @return {@link boolean}
*/
public boolean searchWord(String word) {
TrieNode node = searchNode(word);
if (null != node && node.isLeaf) {
return true;
}
return false;
}
/**
* Static class TrieNode
*
* @author Deepak
*/
public static class TrieNode {
/* Attributes of TrieNode*/
char c;
HashMap<Character, TrieNode> children = new HashMap<>();
boolean isLeaf;
/**
* Default Constructor
*/
public TrieNode() {}
/**
* Parameterized Constructor
* @param c
*/
public TrieNode(char c) {
this.c = c;
}
}
}