class TrieNode{
private char val;
public boolean isEnd;
TrieNode [] next = new TrieNode[26];
public TrieNode(){}
public TrieNode(char val){
this.val=val;
}
}
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(char c:word.toCharArray()){
if(cur.next[c-'a']==null){
cur.next[c - 'a'] = new TrieNode(c);
}
cur=cur.next[c-'a'];
}
cur.isEnd=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode cur = root;
for(char c:word.toCharArray()){
cur = cur.next[c-'a'];
if(cur==null){
return false;
}
}
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(char c:prefix.toCharArray()){
cur=cur.next[c-'a'];
if(cur==null){
return false;
}
}
return true;
}
}
Trie(前缀树)模板
最新推荐文章于 2022-09-06 16:35:45 发布