项目中用到了前缀树来实现敏感词的过滤功能,刚好看到这道题,再来重温一下。
实现一个 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 构成的。
保证所有输入均为非空字符串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
深夜了,明早起来再完成!
这里是通过数组实现了一个tire前缀树,每层数组中保存的是可容纳a,b,c,d...26个英文字母的数组。
如果要实现中文的前缀树,需要使用HashMap<Character,Trie>来实现。
public class leetcode208 {
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
System.out.println(trie.search("apple"));
}
}
class Trie {
private Trie[] next=new Trie[26];
private boolean isEnd=false;
/** Initialize your data structure here. */
public Trie() {}
/** Inserts a word into the trie. */
public void insert(String word) {
char[] arr=word.toCharArray();
Trie t =this;
for(int i=0;i<arr.length;i++){
if(t.next[arr[i]-'a']==null) {
t.next[arr[i]-'a']=new Trie();
}
t=t.next[arr[i]-'a'];
}
t.isEnd=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
char[] arr =word.toCharArray();
Trie t =this;
for(int i=0;i<arr.length;i++){
if(t.next[arr[i]-'a']==null) return false;
t=t.next[arr[i]-'a'];
}
return t.isEnd;
}
/** Returns if there is any word in the trie
* that starts with the given prefix. */
public boolean startsWith(String prefix) {
char[] arr =prefix.toCharArray();
Trie t =this;
for(int i=0;i<arr.length;i++){
if(t.next[arr[i]-'a']==null) return false;
t=t.next[arr[i]-'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);
*/