解法
每一个节点实际上就是一个数组,还需要加上一个isEnd的标志,app,apple,走到app的时候,需要这个isEnd
最开始迷惑的点就是要不要多创建一个TrieNode这个类,还有isEnd标志位没有考虑到。
代码
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 cur=root;
for(int i=0;i<word.length();i++)
{
int temp=word.charAt(i)-'a';
if(cur.arr[temp]==null)
{
cur.arr[temp]=new TrieNode();
}
cur=cur.arr[temp];
}
cur.isEnd=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode cur=root;
for(int i=0;i<word.length();i++)
{
int temp=word.charAt(i)-'a';
if(cur.arr[temp]==null)
{
return false;
}
cur=cur.arr[temp];
}
return cur.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode cur=root;
for(int i=0;i<prefix.length();i++)
{
int temp=prefix.charAt(i)-'a';
if(cur.arr[temp]==null)
{
return false;
}
cur=cur.arr[temp];
}
return true;
}
}
public class TrieNode{
TrieNode[] arr;
boolean isEnd;
public TrieNode() {
arr=new TrieNode[26];
isEnd=false;
}
}
京公网安备 11010502036488号