题目要求:
分析:
首先来了解下什么叫前缀树,请参照这篇博客:
数据结构与算法(十一)Trie字典树
字典树的结构如下图所示:
其中根节点是空的
接下来就来思考如何实现代码。
首先,我们设置一个TrieNode的数据结构,里面包含child和isEnd,它们分别表示子节点(每个节点最多能有26个子节点)和是否是最后一个节点。
在插入word字符串时,从根节点开始。如果根节点的子节点中不包含word字符串的第一个字符,则直接创建一个子节点;如果包含,则就直接指向该子节点,再继续该过程,直到遍历完word字符串为止。当遍历完word字符串之后,我们需要将isEnd置为true,来表示已经插入结束了。
在搜索word字符串时,也从根节点开始。如果根节点的子节点不包含word字符串的第一个字符,就直接返回false,不用做了;如果包含,则指向该子节点,再继续该过程,直到遍历完word字符串为止。当遍历完word字符串之后,需要对isEnd进行判断,如果isEnd为true,则证明确实存在该字符串,返回true;如果isEnd为false,则证明不存在该字符串,返回false。
在判断是否以字符串prefix来start的时候,条件比搜索宽松一点,即:无论isEnd是不是true,它都返回true。
具体代码如下:
class TrieNode {
TrieNode[] child;
boolean isEnd;
public TrieNode() {
this.child = new TrieNode[26];
this.isEnd = false;
}
}
class Trie {
TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode p = root;
for(int i = 0; i < word.length(); i ++) {
char c = word.charAt(i);
if(p.child[c - 'a'] == null) {
p.child[c - 'a'] = new TrieNode();
}
p = p.child[c - 'a'];
}
p.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode p = root;
for(int i = 0; i < word.length(); i ++) {
char c = word.charAt(i);
if(p.child[c - 'a'] == null) {
return false;
}
p = p.child[c - 'a'];
}
/*if(p.isEnd == true) {
return true;
}
return false;*/
return p.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode p = root;
for(int i = 0; i < prefix.length(); i ++) {
char c = prefix.charAt(i);
if(p.child[c - 'a'] == null) {
return false;
}
p = p.child[c - '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);
*/