Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5c1dc3f

Browse files
Implement Trie
1 parent 6284bb2 commit 5c1dc3f

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package leetcode2018;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class ImplementPrefixTree {
7+
private TrieNode root;
8+
/** Initialize your data structure here. */
9+
public ImplementPrefixTree() {
10+
root = new TrieNode('0');
11+
}
12+
13+
/** Inserts a word into the trie. */
14+
public void insert(String word) {
15+
TrieNode currentRoot = root;
16+
int i = 0;
17+
for(char c: word.toCharArray()){
18+
if(!currentRoot.children.containsKey(c)){
19+
TrieNode node = new TrieNode(c);
20+
currentRoot.children.put(c, node);
21+
}
22+
23+
currentRoot = currentRoot.children.get(c);
24+
i++;
25+
currentRoot.word = word.substring(0,i);
26+
if(word.length()==i){
27+
currentRoot.isComplete = true;
28+
}
29+
30+
}
31+
}
32+
33+
/** Returns if the word is in the trie. */
34+
public boolean search( String word) {
35+
TrieNode node = searchHelper(word);
36+
if(node==null) return false;
37+
return node.isComplete;
38+
}
39+
40+
/** Returns if there is any word in the trie that starts with the given prefix. */
41+
public boolean startsWith(String prefix) {
42+
return searchHelper(prefix)!=null;
43+
}
44+
45+
public TrieNode searchHelper(String word){
46+
TrieNode node = root;
47+
for(char c: word.toCharArray()){
48+
if(node.children.containsKey(c)){
49+
node = node.children.get(c);
50+
}else {
51+
return null;
52+
}
53+
}
54+
return node;
55+
}
56+
57+
58+
class TrieNode{
59+
char val;
60+
Map<Character, TrieNode> children;
61+
String word;
62+
boolean isComplete;
63+
TrieNode(char val){
64+
this.val=val;
65+
this.children = new HashMap<>();
66+
this.word= "";
67+
this.isComplete = false;
68+
}
69+
}
70+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /