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 构成的。
- 保证所有输入均为非空字符串。
思路
代码
public class Trie {
private class Node{
Node[] childs = new Node[26];
boolean isLeaf =false;
}
private Node root = new Node();
/**
* Initialize your data structure here.
*/
public Trie() {
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
Node current=root;
for (int i = 0; i < word.length(); i++) {
int index=word.charAt(i)-'a';
if (current.childs[index]==null){
current.childs[index]=new Node();
}
current=current.childs[index];
}
current.isLeaf=true;
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
Node current = root;
for (int i = 0; i < word.length(); i++) {
int index=word.charAt(i)-'a';
if (current.childs[index]==null){
return false;
}
current=current.childs[index];
}
return current.isLeaf;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
Node current = root;
for (int i = 0; i < prefix.length(); i++) {
int index=prefix.charAt(i)-'a';
if (current.childs[index]==null){
return false;
}
current=current.childs[index];
}
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);
*/
应用
- 自动补全
- 拼写检查
- IP路由(最长前缀匹配)
- T9 (九宫格) 打字预测
- 单词游戏
相似题目
- LeetCode-211添加与搜索单词 : 一个 Trie 树的直接应用。
- LeetCode-212 单词搜索II:类似 Boggle 的游戏。

浙公网安备 33010602011771号