实现一个 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 构成的。 保证所有输入均为非空字符串。
思路:
前缀树是什么?先来看看百度百科:
又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
它有3个基本性质:
根节点不包含字符,除根节点外每一个节点都只包含一个字符; 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串; 每个节点的所有子节点包含的字符都不相同。
通过这个我们可以得知,就是从树的顶端到到末端组成一个单词,每一层的节点包含一个字母。我们只需要从根节点开始向下遍历查找即可,但是有的单词又是别的单词的前缀,这样查找可能会有错误。所以,设置一个标志位isEnd来判断是否有单词在这里结束。
所以,我们可以写出Trie的数据结构:
class Trie{
boolean isEnd;
Trie[] children;
}
这样一来每个节点的数据结构就有了。下面就是插入和查找逻辑:
-
插入:
假如要插入单词app,那么就看根节点的children[‘a’-‘a’]是否为空,为空就新建一个Trie节点插入进去。不为空就查看该节点的children[‘p’-‘a’]是否为空,然后依次类推……注意,在最后一个字母的时候,将标志位isEnd置为true,表明自己在这里结束。 -
查询
从根节点向下查询,一旦插到所需要位置的节点为空,就返回false。到最后一个字母时,判断标志位是否因为true。
startWith()则不需要判断isEnd。
代码如下:
class Trie {
boolean isEnd;
Trie[] children;
/** Initialize your data structure here. */
public Trie() {
isEnd=false;
children = new Trie[26];
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie node = this;
for(int i=0;i<word.length();i++){
char curr = word.charAt(i);
if(node.children[curr-'a']==null){ //如果为空新建一个
node.children[curr-'a'] = new Trie();
}
node = node.children[curr-'a'];
}
//插入完所有节点后,将最后一个isEnd置为true
node.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie node = this;
for(int i=0;i<word.length();i++){
char curr = word.charAt(i);
if(node.children[curr-'a']==null){ //如果为空新建一个
return false;
}
node = node.children[curr-'a'];
}
if(node.isEnd!=true) return false;
return true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie node = this;
for(int i=0;i<prefix.length();i++){
char curr = prefix.charAt(i);
if(node.children[curr-'a']==null){ //如果为空新建一个
return false;
}
node = node.children[curr-'a'];
}
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);
*/