实现一个 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
构成的。 - 保证所有输入均为非空字符串。
class TrieNode{
private TrieNode[] links=new TrieNode[26];
private boolean isLeaf;
public boolean contains(char c){
return links[c-'a']!=null;
}
public TrieNode get(char c){
return links[c-'a'];
}
public void set(TrieNode root,char c){
links[c-'a']=root;
}
public boolean isLeaf() {
return isLeaf;
}
public void setLeaf(boolean leaf) {
isLeaf = leaf;
}
}
class Trie {
TrieNode root;
public Trie() {
root=new TrieNode();
}
public void insert(String word) {
TrieNode node=root;
for (int i = 0; i < word.length(); i++) {
if(!node.contains(word.charAt(i))){
node.set(new TrieNode(),word.charAt(i));
}
node=node.get(word.charAt(i));
}
node.setLeaf(true);
}
public boolean search(String word) {
TrieNode node=root;
for (int i = 0; i < word.length(); i++) {
if(!node.contains(word.charAt(i))){
return false;
}
node=node.get(word.charAt(i));
}
return node.isLeaf();
}
public boolean startsWith(String prefix) {
TrieNode node=root;
for (int i = 0; i < prefix.length(); i++) {
if(!node.contains(prefix.charAt(i))){
return false;
}
node=node.get(prefix.charAt(i));
}
return true;
}
}