forked from christine-1017/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
62 lines (55 loc) · 1.67 KB
/
Trie.java
File metadata and controls
62 lines (55 loc) · 1.67 KB
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
class TrieNode {
// Initialize your data structure here.
public TrieNode[] edges;
public boolean isLeaf; //check if a trienode is a leaf node
public TrieNode() {
// all possible sons
edges = new TrieNode[26];
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
if (word == null || word.length() == 0) {
return;
}
root = insert(root, word, 0);
}
public TrieNode insert(TrieNode node, String word, int len) {
if (node == null) {
node = new TrieNode();
}
if (len == word.length()) {
node.isLeaf = true;
return node;
}
int pos = word.charAt(len) - 'a';
node.edges[pos] = insert(node.edges[pos], word, len + 1);
return node;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode temp = searchHelper(root, word, 0);
return temp == null ? false : temp.isLeaf;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode temp = searchHelper(root, prefix, 0);
return temp == null ? false : true;
}
public TrieNode searchHelper(TrieNode node, String word, int len) {
if (node == null) {
return null;
}
if (len == word.length()) {
return node;
}
int pos = word.charAt(len) - 'a';
return searchHelper(node.edges[pos], word, len + 1);
}
}