Leetcode 208.实现前缀树

时间:2022-04-15 05:03:14

实现前缀树

实现一个 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 构成的。
  • 保证所有输入均为非空字符串。
 dclass TrieNode{
char c;
boolean leaf;
HashMap<Character,TrieNode> children=new HashMap<Character,TrieNode>();
public TrieNode(char c){
this.c=c;
}
public TrieNode(){};
} public class Trie{
private TrieNode root;
public Trie(){
root=new TrieNode();
} public void insert(String word){
Map<Character,TrieNode> children=root.children;
for(int i=0;i<word.length();i++){
char c=word.charAt(i);
TrieNode t;
if(children.containsKey(c)){
t=children.get(c);
}else{
t=new TrieNode(c);
children.put(c,t);
}
children=t.children;
if(i==word.length()-1)
t.leaf=true;
}
} public boolean search(String word){
TrieNode t=searchNode(word);
return t!=null && t.leaf;
} private TrieNode searchNode(String word){
Map<Character,TrieNode> children=root.children;
TrieNode t=null;
for(int i=0;i<word.length();i++){
char c=word.charAt(i);
if(!children.containsKey(c)) return null;
t=children.get(c);
children=t.children;
}
return t;
} public boolean startsWith(String prefix){
return searchNode(prefix)!=null;
}
}