Skip to content

Commit 1cc9920

Browse files
author
sailok.chinta
committed
feat: add Trie class
1 parent 7a5a9e3 commit 1cc9920

File tree

1 file changed

+121
-0
lines changed
  • src/main/java/com/thealgorithms/tries

1 file changed

+121
-0
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
package com.thealgorithms.tries;
2+
3+
/**
4+
* TrieNode class which holds the lowercase letter and references to its child nodes
5+
*/
6+
class TrieNode {
7+
private static final int CHILDREN_NODE_COUNT = 26;
8+
9+
private TrieNode[] children;
10+
private char letter;
11+
private boolean end;
12+
13+
public TrieNode(char letter) {
14+
this.letter = letter;
15+
this.children = new TrieNode[CHILDREN_NODE_COUNT];
16+
this.end = false;
17+
}
18+
19+
public TrieNode[] getChildren() {
20+
return children;
21+
}
22+
23+
public void setChildren(TrieNode[] children) {
24+
this.children = children;
25+
}
26+
27+
public char getLetter() {
28+
return letter;
29+
}
30+
31+
public void setLetter(char letter) {
32+
this.letter = letter;
33+
}
34+
35+
public boolean isEnd() {
36+
return end;
37+
}
38+
39+
public void setEnd(boolean end) {
40+
this.end = end;
41+
}
42+
}
43+
44+
/**
45+
* Trie class which holds Strings of LowerCase Sensitive characters.
46+
*/
47+
public class Trie {
48+
private static final char ROOT_CHAR = '*';
49+
private static final char BASE_CHAR = 'a';
50+
51+
private final TrieNode root;
52+
53+
public Trie() {
54+
this.root = new TrieNode(ROOT_CHAR);
55+
}
56+
57+
/**
58+
* Inserts the word into Trie
59+
*
60+
* @param word
61+
*/
62+
public void insert(String word) {
63+
TrieNode head = root;
64+
65+
for (int i = 0; i < word.length(); i++) {
66+
char c = word.charAt(i);
67+
68+
if (head.getChildren()[c - BASE_CHAR] == null) {
69+
head.getChildren()[c - BASE_CHAR] = new TrieNode(c);
70+
}
71+
72+
head = head.getChildren()[c - BASE_CHAR];
73+
}
74+
75+
head.setEnd(true);
76+
}
77+
78+
/**
79+
* Searches in the Trie if a word exists or not.
80+
*
81+
* @param word
82+
* @return true / false
83+
*/
84+
public boolean search(String word) {
85+
TrieNode head = root;
86+
87+
for (int i = 0; i < word.length(); i++) {
88+
char c = word.charAt(i);
89+
90+
if (head.getChildren()[c - BASE_CHAR] == null) {
91+
return false;
92+
}
93+
94+
head = head.getChildren()[c - BASE_CHAR];
95+
}
96+
97+
return head.isEnd();
98+
}
99+
100+
/**
101+
* Searches in the Trie if a prefix exists or not.
102+
*
103+
* @param prefix
104+
* @return true / false
105+
*/
106+
public boolean startsWith(String prefix) {
107+
TrieNode head = root;
108+
109+
for (int i = 0; i < prefix.length(); i++) {
110+
char c = prefix.charAt(i);
111+
112+
if (head.getChildren()[c - BASE_CHAR] == null) {
113+
return false;
114+
}
115+
116+
head = head.getChildren()[c - BASE_CHAR];
117+
}
118+
119+
return true;
120+
}
121+
}

0 commit comments

Comments
 (0)