实现 Trie (前缀树)
Category Difficulty Likes Dislikes
algorithms Medium (63.21%) 175 -
Tags
Companies
实现一个 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 构成的。
- 保证所有输入均为非空字符串。
分析
import java.util.Map;
/*
* @lc app=leetcode.cn id=208 lang=java
*
* [208] 实现 Trie (前缀树)
*/
// @lc code=start
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) {
char[] chas = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0; i < chas.length; i++){
index = chas[i] - 'a'; //该字符对应map的位置
if(node.map[index] == null){ //map没有存储该子节点,则新建
node.map[index] = new TrieNode();
}
node = node.map[index];
node.path++;
}
node.end++;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
char[] chas = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0; i < chas.length; i++){
index = chas[i] - 'a';
if(node.map[index] == null){
return false;
}
node = node.map[index];
}
if(node.end > 0){
return true;
}
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
char[] chas = prefix.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0; i < chas.length; i++){
index = chas[i] - 'a';
if(node.map[index] == null){
return false;
}
node = node.map[index];
}
return true;
}
}
class TrieNode {
public int path; //经过该节点的字符串数量
public int end; //以该节点结尾的字符串数量
public TrieNode[] map; //保存其子节点
public TrieNode(){
path = 0;
end = 0;
map = new TrieNode[26];
}
}
/**
* 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);
*/
// @lc code=end