Skip to content

Commit 4e54818

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 208_Implement_Trie_(Prefix Tree).java
1 parent 8de32fc commit 4e54818

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
class TrieNode {
2+
private Map<Character, TrieNode> children;
3+
private boolean isWord;
4+
5+
public TrieNode() {
6+
children = new HashMap<>();
7+
isWord = false;
8+
}
9+
10+
public boolean isWord() {
11+
return isWord;
12+
}
13+
14+
public void isFullWord() {
15+
isWord = true;
16+
}
17+
18+
public void putCharIfAbsent(char c) {
19+
children.putIfAbsent(c, new TrieNode());
20+
}
21+
22+
public TrieNode getChild(char c) {
23+
return children.get(c);
24+
}
25+
}
26+
27+
class Trie {
28+
private TrieNode root;
29+
30+
/** Initialize your data structure here. */
31+
public Trie() {
32+
root = new TrieNode();
33+
}
34+
35+
/** Inserts a word into the trie. */
36+
public void insert(String word) {
37+
if (word == null) {
38+
return;
39+
}
40+
41+
TrieNode curr = root;
42+
for (char c : word.toCharArray()) {
43+
curr.putCharIfAbsent(c);
44+
curr = curr.getChild(c);
45+
}
46+
47+
curr.isFullWord();
48+
}
49+
50+
/** Returns if the word is in the trie. */
51+
public boolean search(String word) {
52+
if (word == null) {
53+
return false;
54+
}
55+
56+
TrieNode curr = root;
57+
58+
for (char c : word.toCharArray()) {
59+
curr = curr.getChild(c);
60+
61+
if (curr == null) {
62+
return false;
63+
}
64+
}
65+
66+
return curr.isWord();
67+
}
68+
69+
/**
70+
* Returns if there is any word in the trie that starts with the given prefix.
71+
*/
72+
public boolean startsWith(String prefix) {
73+
if (prefix == null) {
74+
return false;
75+
}
76+
77+
TrieNode curr = root;
78+
79+
for (char c : prefix.toCharArray()) {
80+
curr = curr.getChild(c);
81+
if (curr == null) {
82+
return false;
83+
}
84+
}
85+
86+
return true;
87+
}
88+
}

0 commit comments

Comments
 (0)