知识点
Trie (发音为 "try") 或前缀树是一种树数据结构,用于检索字符串数据集中的键。
常见的应用场景有:
- 自动补全
- 拼写检查
- IP路由(最长前缀匹配)
- 打字预测
示例
- 实现 Trie (前缀树)
class TrieNode {
private final int R = 26;
private TrieNode[] links;
private boolean isEnd = false;
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 boolean isEnd() {
return isEnd;
}
public void setEnd() {
isEnd = true;
}
}
class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node = root;
char[] charArray = word.toCharArray();
int len = charArray.length;
for (int i=0;i<len;i++) {
if (!node.containsKey(charArray[i])) {
node.put(charArray[i], new TrieNode());
}
node=node.get(charArray[i]);
}
node.setEnd();
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = root;
char[] charArray = word.toCharArray();
int len = charArray.length;
for (int i=0;i<len;i++) {
if (!node.containsKey(charArray[i])) {
return false;
}
node=node.get(charArray[i]);
}
return node.isEnd();
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = root;
char[] charArray = prefix.toCharArray();
int len = charArray.length;
for (int i=0;i<len;i++) {
if (!node.containsKey(charArray[i])) {
return false;
}
node=node.get(charArray[i]);
}
return true;
}
}