题目:
Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
示例:
输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]
解释
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
思路:
又是设计类的题目,记得做了一个LRU缓存的还有一个什么.
一定要先明白他的数据结构再下手。
本题的前缀树也可以称之为字典树
也可以简化为
复杂度:
时间复杂度:O(n)
空间复杂度:O(1)
代码:
//trie是字典树指向子节点的指针数组children,长度为26,即英文字母个数,还需要一个标记指出是否已达结尾
private Trie[] children;
private boolean isEnd;
public Trie() {
children = new Trie[26];
isEnd = false;
}
//实现插入单词的功能
public void insert(String word) {
Trie node = this;
//遍历字符
for(int i = 0;i < word.length();++i){
char ch = word.charAt(i);
int index = ch - 'a';
//匹配到前缀链没有对应的字符,就开辟新的节点
if(node.children[index] == null){
node.children[index] = new Trie();
}
node = node.children[index];
}
node.isEnd = true;
}
//查找Trie中是否存在word
public boolean search(String word) {
Trie node = this;
//从根节点的子结点向下匹配,若结点为null就返回false
for(int i = 0;i < word.length();++i){
char ch = word.charAt(i);
node = node.children[ch-'a'];
if(node == null) return false;
}
return node.isEnd;
}
//判断Trie中是否有以prefix为前缀的单词
public boolean startsWith(String prefix) {
Trie node = this;
for(int i = 0;i < prefix.length();++i){
char ch = prefix.charAt(i);
node = node.children[ch-'a'];
if(node == null) return false;
}
//这个不用遍历到结尾
return true;
}