Fork me on GitHub

Implement Trie

Linkage

Implement Trie (Prefix Tree)

Reminder

1.This is a naive implementation of Trie, which do not support the delete function, furthermore, the long string which can match multiple words is also not supported.

2.The key and value of a map must be Object, the basic type like int and char is not supported.

Code

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
import java.util.HashMap;

class TrieNode {
boolean isWord;
HashMap<Character, TrieNode> charToTrieNode;
public TrieNode() {
isWord = false;
charToTrieNode = new HashMap<Character, TrieNode>();
}
}


public class Trie {

TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}

/** Inserts a word into the trie. */
public void insert(String word) {
int word_len = word.length();
TrieNode traverseNode = root;
for (int index = 0; index < word_len; index++) {
Character ch = word.charAt(index);
TrieNode target = traverseNode.charToTrieNode.get(ch);
if (target == null){
target = new TrieNode();
traverseNode.charToTrieNode.put(ch, target);
}
traverseNode = target;
}
traverseNode.isWord = true;
}

/** Returns if the word is in the trie. */
public boolean search(String word) {
int word_len = word.length();
TrieNode traverseNode = root;
for (int index = 0; index < word_len; index++) {
Character ch = word.charAt(index);
TrieNode target = traverseNode.charToTrieNode.get(ch);
if (target == null){
return false;
}
traverseNode = target;
}

return traverseNode.isWord;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
int word_len = prefix.length();
TrieNode traverseNode = root;
for (int index = 0; index < word_len; index++) {
Character ch = prefix.charAt(index);
TrieNode target = traverseNode.charToTrieNode.get(ch);
if (target == null){
return false;
}
traverseNode = target;
}
return true;
}
}