实现类:
public class Trie {
private class TrieNode {
//元素的序号
int level;
//子节点信息
TrieNode[] children = new TrieNode[26];
//是否是最后一个节点
public boolean isLast;
//出现的频率
public int fre = 1;
}
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String str) {
char[] chars = str.toCharArray();
TrieNode p = root;
//遍历单词的每个字符
for (int i = 0; i < chars.length; ++i) {
char c = chars[i];
TrieNode child = p.children[c - 'a'];
if (child == null) {
TrieNode node = new TrieNode();
node.level = i;
p.children[c - 'a'] = node;
p = node;
} else {
p = child;
++child.fre;
}
}
p.isLast = true;
}
//输出以prefix为前缀的所有后缀
public void print(String prefix, TrieNode p) {
if (p.isLast && prefix.length() > 0) {
System.out.println(prefix);
}
for (int i = 0; i < 26; ++i) {
if (p.children[i] != null) {
print(prefix + (char) ('a' + i), p.children[i]);
}
}
}
//查找以prefix为前缀的所有后缀
public void search(String prefix) {
char[] chars = prefix.toCharArray();
TrieNode p = root;
for (int i = 0; i < chars.length; ++i) {
char c = chars[i];
TrieNode child = p.children[c - 'a'];
if (child == null) {
return;
} else {
p = child;
}
}
print("", p);
}
}
测试类:
import org.junit.Before;
import org.junit.Test;
public class TrieTest {
Trie trie = new Trie();
@Before
public void insert() {
trie.insert("hit");
trie.insert("hat");
trie.insert("had");
trie.insert("have");
trie.insert("hate");
}
@Test
public void print() {
trie.print("", trie.root);
}
@Test
public void search() {
trie.search("ha");
}
}