LeetCode - 208. 实现 Trie (前缀树)(字典树)
题目:
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。
保证所有输入均为非空字符串。
Trie 树的结点结构
Trie 树是一个有根的树,其结点具有以下字段:。
最多 R 个指向子结点的链接,其中每个链接对应字母表数据集中的一个字母。
本文中假定 R 为 26,小写拉丁字母的数量。
布尔字段,以指定节点是对应键的结尾还是只是键前缀。
Trie树的节点结构代码:
class TrieNode {
// R links to node children
private TrieNode[] links;
private final int R = 26;
private boolean isEnd;
public TrieNode() {
links = new TrieNode[R];
}
public boolean containsKey(char ch) {
return links[ch -'a'] != null;
}
public TrieNode get(char ch) {
return links[ch -'a'];
}
public void put(char ch, TrieNode node) {
links[ch -'a'] = node;
}
public void setEnd() {
isEnd = true;
}
public boolean isEnd() {
return isEnd;
}
}
向 Trie 树中插入键:
在 Trie 树中查找键:
class Trie {
...
// search a prefix or whole key in trie and
// returns the node where search ends
private TrieNode searchPrefix(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char curLetter = word.charAt(i);
if (node.containsKey(curLetter)) {
node = node.get(curLetter);
} else {
return null;
}
}
return node;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEnd();
}
}
查找 Trie 树中的键前缀:
class Trie {
...
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode node = searchPrefix(prefix);
return node != null;
}
}
LeetCode 208题 完整代码:
class Trie {
Trie[] next = new Trie[26];
boolean isEnd = false;
public Trie(){
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie curr = this;
for (char c : word.toCharArray()) {
if (curr.next[c - 'a'] == null){
curr.next[c - 'a'] = new Trie();
}
curr = curr.next[c - 'a'];
}
curr.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie curr = this;
for (char c : word.toCharArray()) {
if (curr.next[c - 'a'] == null){
return false;
}
curr = curr.next[c - 'a'];
}
return curr.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie curr = this;
for (char c : prefix.toCharArray()) {
if (curr.next[c - 'a'] == null){
return false;
}
curr = curr.next[c - 'a'];
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/
知识点: