实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
- R向单词查找树
根结点没有存放任何字符,每个结点都包含下一个可能出现的所有字符的链接。从根结点开始首先经过了键的首字母所对应的链接,如此这般沿着结点不断前进,直到到达键的最后一个字符或是遇到一条空链接。
public class Trie {
private static final int R = 26;
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
this.root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode t = root;
for (char c : word.toCharArray()) {
int i = c - 'a';
if (t.children[i] == null) {
t.children[i] = new TrieNode();
}
t = t.children[i];
}
t.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode t = root;
for (char c : word.toCharArray()) {
int i = c - 'a';
if (t.children[i] == null) {
return false;
}
t = t.children[i];
}
return t.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode t = root;
for (char c : prefix.toCharArray()) {
int i = c - 'a';
if (t.children[i] == null) {
return false;
}
t = t.children[i];
}
return true;
}
static class TrieNode {
TrieNode[] children;
boolean isWord;
TrieNode() {
this.children = new TrieNode[R];
this.isWord = false;
}
}
}
- 三向单词查找树
在三向单词查找树中,每个结点都含有一个字符、三条链接和一个值。这三条链接分别对应当前字符小于父结点、以父结点开头、大于父结点字符的所有键。字符是显式地保存在结点中的,父结点的三个链接中只有一条链接和当前字符匹配,选择匹配的链接并不断沿着路径向下(在代码中将看到只有选择了中间链接才能检查下一个字符,沿着路径向下前进)。
public class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
this.root = insert(word, root, 0);
}
TrieNode insert(String word, TrieNode t, int i) {
char ch = word.charAt(i);
if (t == null) {
t = new TrieNode();
t.ch = ch;
}
if (ch < t.ch) {
t.left = insert(word, t.left, i);
} else if (ch > t.ch) {
t.right = insert(word, t.right, i);
} else if (i < word.length() - 1) {
t.mid = insert(word, t.mid, i + 1);
} else {
t.isWord = true;
}
return t;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode t = search(word, root, 0);
return t == null ? false : t.isWord;
}
TrieNode search(String word, TrieNode t, int i) {
if (t == null) {
return t;
}
char ch = word.charAt(i);
if (ch < t.ch) {
return search(word, t.left, i);
} else if (ch > t.ch) {
return search(word, t.right, i);
} else if (i < word.length() - 1) {
return search(word, t.mid, i + 1);
}
return t;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode t = search(prefix, root, 0);
return t != null;
}
static class TrieNode {
char ch;
TrieNode left, mid, right;
boolean isWord = false;
}
}