【字典树】208. 实现 Trie (前缀树)
题目:
实现一个 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
解答:
`class Trie {
private final int SIZE = 26;
private Trie[] childern = new Trie[SIZE];
private boolean isEnd = false;
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie tmp = this;
for(int i = 0;i<word.length();i++){
int cur = word.charAt(i) - 'a';
if(tmp.childern[cur] == null){
tmp.childern[cur] = new Trie();
}
tmp = tmp.childern[cur];
}
tmp.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie tmp = this;
for(int i = 0;i<word.length();i++){
int cur = word.charAt(i) - 'a';
if(tmp.childern[cur] == null){
return false;
}
tmp = tmp.childern[cur];
}
return tmp.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie tmp = this;
for(int i = 0;i<prefix.length();i++){
int cur = prefix.charAt(i) - 'a';
if(tmp.childern[cur] == null){
return false;
}
tmp = tmp.childern[cur];
}
return true;
}
}`

浙公网安备 33010602011771号