Skip to content

Commit 07a1a0d

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 208_Implement_Trie_(Prefix Tree).java
1 parent d4c2009 commit 07a1a0d

File tree

1 file changed

+23
-55
lines changed

1 file changed

+23
-55
lines changed
Lines changed: 23 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,88 +1,56 @@
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-
271
class Trie {
282
private TrieNode root;
293

30-
/** Initialize your data structure here. */
314
public Trie() {
325
root = new TrieNode();
336
}
347

35-
/** Inserts a word into the trie. */
368
public void insert(String word) {
37-
if (word == null) {
38-
return;
39-
}
9+
TrieNode runner = root;
4010

41-
TrieNode curr = root;
4211
for (char c : word.toCharArray()) {
43-
curr.putCharIfAbsent(c);
44-
curr = curr.getChild(c);
12+
runner.children.putIfAbsent(c, new TrieNode());
13+
runner = runner.children.get(c);
4514
}
4615

47-
curr.isFullWord();
16+
runner.isWord = true;
4817
}
4918

50-
/** Returns if the word is in the trie. */
5119
public boolean search(String word) {
52-
if (word == null) {
53-
return false;
54-
}
55-
56-
TrieNode curr = root;
20+
TrieNode runner = root;
5721

5822
for (char c : word.toCharArray()) {
59-
curr = curr.getChild(c);
60-
61-
if (curr == null) {
23+
if (runner.children.get(c) == null) {
6224
return false;
6325
}
26+
27+
runner = runner.children.get(c);
6428
}
6529

66-
return curr.isWord();
30+
return runner.isWord;
6731
}
6832

69-
/**
70-
* Returns if there is any word in the trie that starts with the given prefix.
71-
*/
7233
public boolean startsWith(String prefix) {
73-
if (prefix == null) {
74-
return false;
75-
}
76-
77-
TrieNode curr = root;
34+
TrieNode runner = root;
7835

7936
for (char c : prefix.toCharArray()) {
80-
curr = curr.getChild(c);
81-
if (curr == null) {
37+
if (runner.children.get(c) == null) {
8238
return false;
8339
}
40+
41+
runner = runner.children.get(c);
8442
}
8543

8644
return true;
8745
}
46+
47+
private class TrieNode {
48+
private Map<Character, TrieNode> children;
49+
private boolean isWord;
50+
51+
public TrieNode() {
52+
children = new HashMap<>();
53+
isWord = false;
54+
}
55+
}
8856
}

0 commit comments

Comments
 (0)