功能描述
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
1 <= word.length, prefix.length <= 2000
word 和 prefix 仅由小写英文字母组成
insert、search 和 startsWith 调用次数 总计 不超过 3 * 104 次
设计思路
注意到,字符串其实是26个小写英文字母的排列组合。有26^N种情况,其中N是 word.length,所以可以用一个二维数组或者链表结构表示全体数据集合,因为字符长度可能很长也可能很短,如果采用二维数组,一开始需要向内存申请超长的空间,所以这里采用链表结构,用next指针表示下一个位置的节点。
节点的设计,用长度为26的数组表示每个字母c(字母c对应于数组中的位置index = c - ‘a’),用布尔型变量isEnd表示是否到了字符串终点 (减少)。
insert方法
每插入一个单词,注意将该单词末尾对应的节点的布尔型变量isEnd设置为true;
search方法
判断当前树有没有对应的支,并看末尾节点isEnd是否为true
startsWith方法
判断当前树有没有对应的支
代码实现
public class Trie {
Trie[] next;
boolean isEnd;
public Trie() {
this.next = new Trie[26];
}
public void insert(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
if (node.next[c - 'a'] == null) {
node.next[c - 'a'] = new Trie();
}
node = node.next[c - 'a'];
}
node.isEnd = true;
}
public boolean search(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
if (node.next[c - 'a'] == null) {
return false;
}
node = node.next[c - 'a'];
}
return node.isEnd;
}
public boolean startsWith(String prefix) {
Trie node = this;
for (char c : prefix.toCharArray()) {
if (node.next[c - 'a'] == null) {
return false;
}
node = node.next[c - 'a'];
}
return true;
}
}