Implement a trie with insert
, search
, and startsWith
methods.
trie树实现
java
class TrieNode {
TrieNode[] children;
boolean hasWord;
public TrieNode() {
children = new TrieNode[26];
hasWord = false;
}
public void insert(String str, int index) {
if (index == str.length()) {
hasWord = true;
return;
}
int pos = str.charAt(index) - 'a';
if (children[pos] == null) {
children[pos] = new TrieNode();
}
children[pos].insert(str, index + 1);
}
public TrieNode find(String str, int index) {
if (index == str.length()) {
return this;
}
int pos = str.charAt(index) - 'a';
if (children[pos] == null) {
return null;
}
return children[pos].find(str, index + 1);
}
}
public class Trie {
/** Initialize your data structure here. */
TrieNode root;
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
root.insert(word, 0);
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = root.find(word, 0);
return (node != null && node.hasWord);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = root.find(prefix, 0);
return node != null;
}
}
/**
* 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);
*/