Implement a trie with insert
, search
, and startsWith
methods.
Example:
Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true
Note:
- You may assume that all inputs are consist of lowercase letters
a-z
. - All inputs are guaranteed to be non-empty strings.
单词查找树,由于分支太多,用数组实现分支
class Trie {
class TrieNode{
boolean existString;
TrieNode[] children = new TrieNode[26];
}
TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode p = root;
for(int i = 0;i<word.length();i++){
if( p.children[word.charAt(i)-'a']==null ){
p.children[word.charAt(i)-'a'] = new TrieNode();
}
p = p.children[word.charAt(i)-'a'];
}
p.existString = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode p = root;
for(int i = 0;i<word.length();i++){
if( p.children[word.charAt(i)-'a']==null ){
return false;
}
p = p.children[word.charAt(i)-'a'];
}
return p.existString;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode p = root;
for(int i = 0;i<prefix.length();i++){
if( p.children[prefix.charAt(i)-'a']==null ){
return false;
}
p = p.children[prefix.charAt(i)-'a'];
}
return true;
}
}
/**
* 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);
*/