只包含英文小写字母的trie树的java实现

trie树是自然语言处理中经常用到的数据结构,之前没接触过,感觉比较困难。这里用Java实现一个最简单版本的trie树(LintCode, LeetCode),包含三个方法insert, search和startWith。更高效更复杂版本的trie树之后再研究吧。

参考代码:

1
2
3
4
5
6
7
8
9
10
11
12

* TrieNode.java
* Created by shenhuaze on 2018/5/20.
*/
public class {
TrieNode[] children;
boolean isLeaf;
public () {
this.children = new TrieNode[26];
this.isLeaf = false;
}
}
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

* Trie.java
* Created by shenhuaze on 2018/5/20.
*/
public class Trie {
TrieNode root;
public Trie() {
// do intialization if necessary
root = new TrieNode();
}

/*
* @param word: a word
* @return: nothing
*/
public void insert(String word) {
// write your code here
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
int offset = word.charAt(i) - 'a';
if (curr.children[offset] == null) {
curr.children[offset] = new TrieNode();
}
curr = curr.children[offset];
}
curr.isLeaf = true;
}

/*
* @param word: A string
* @return: if the word is in the trie.
*/
public boolean search(String word) {
// write your code here
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
int offset = word.charAt(i) - 'a';
if (curr.children[offset] == null) {
return false;
}
curr = curr.children[offset];
}
return curr.isLeaf;
}

/*
* @param prefix: A string
* @return: if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
// write your code here
TrieNode curr = root;
for (int i = 0; i < prefix.length(); i++) {
int offset = prefix.charAt(i) - 'a';
if (curr.children[offset] == null) {
return false;
}
curr = curr.children[offset];
}
return true;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13

* DemoTest.java
* Created by shenhuaze on 2018/5/20.
*/
public class DemoTest {
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("hello");
System.out.println(trie.search("hello"));
System.out.println(trie.startsWith("hell"));
System.out.println(trie.search("world"));
}
}

运行结果:

1
2
3
true
true
false