版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Viscu/article/details/82590670
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
emmmm….基本操作,用一个flag记录当前位置是否是一个完整串或者直接判断String是否为null.
class Trie {
Trie[] next;
String word=null; //判断是否是一个完整的串
/** Initialize your data structure here. */
public Trie() {
next=new Trie[26];
}
/** Inserts a word into the trie. */
public void insert(String word) {
if(word==null||word.equals("")){
return;
}
Trie cur=this;
for(char ch:word.toCharArray()){ //遍历
if(cur.next[ch-'a']==null){
cur.next[ch-'a']=new Trie();
}
cur=cur.next[ch-'a'];
}
cur.word=word; //设置串的识别标志
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie cur=this;
for(char ch:word.toCharArray()){
if(cur.next[ch-'a']==null){ //说明没有这个串 直接放回
return false;
}
cur=cur.next[ch-'a'];
}
if(cur.word==null){ //只是前缀 不是一个完整串
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 cur=this;
for(char ch:prefix.toCharArray()){
if(cur.next[ch-'a']==null){
return false;
}
cur=cur.next[ch-'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);
*/