题目描述(题目链接)
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
- Trie() 初始化前缀树对象。
- void insert(String word) 向前缀树中插入字符串 word。
- boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false。
- boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false。
求解思路
前缀树/字典树定义
主要考察的是前缀树的数据结构设计:
- children数组:用长度为26的数组,分别对应的是a、b、c…z字母对应的子节点。(这里我刚开始是选择的ch和arraylist分别存储节点的字母和子节点。看了题解,这样设计在insert和search时可直接查询到当前字母是否存在,复杂度为O(1),绝绝子!是我蠢了蠢了蠢了)
- isend布尔变量:用isend标记该节点是否是一个单词的最后一个字母。
代码
class Trie {
Trie[] children;
boolean isend;
/** Initialize your data structure here. */
public Trie() {
this.isend = false; //初始赋为false
children = new Trie[26]; //长度都为26
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie tr = this;
for(int i=0;i<word.length();i++){
int ch = word.charAt(i)-'a';
if(tr.children[ch]==null) tr.children[ch] = new Trie(); //没有就创建一个,有就不用了
tr = tr.children[ch]; //指向下一个结点
}
tr.isend = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
int i = 0;
Trie tr = this;
for(;i<word.length();i++){
int ch = word.charAt(i)-'a';
if(tr.children[ch]==null) return false; //没有,直接返回false
tr = tr.children[ch]; //指向下一个结点
}
if(tr.isend) return true; //要判断一下是否是一个单词的最后一个字母
else return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) { //跟search差不多
int i = 0;
Trie tr = this;
for(;i<prefix.length();i++){
int ch = prefix.charAt(i)-'a';
if(tr.children[ch]==null) return false;
tr = tr.children[ch];
}
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);
*/