Description:
Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
实现一个简单的Trie树,参考我的博客:http://www.cnblogs.com/wxisme/p/4876197.html
class TrieNode {
public TrieNode[] son;
public boolean isEnd;
// Initialize your data structure here.
public TrieNode() {
this.son = new TrieNode[26];
isEnd = false; }
} public class Trie {
private TrieNode root; public Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
public void insert(String word) {
char[] wordChars = word.toCharArray();
TrieNode node = this.root;
for(char ch : wordChars) {
int pos = ch - 'a';
if(node.son[pos] == null) {
node.son[pos] = new TrieNode();
}
node = node.son[pos];
}
node.isEnd = true;
} // Returns if the word is in the trie.
public boolean search(String word) {
char[] wordChars = word.toCharArray();
TrieNode node = this.root;
for(char ch : wordChars) {
int pos = ch - 'a';
if(node.son[pos] == null) {
return false;
}
node = node.son[pos];
}
return node.isEnd;
} // Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) { char[] prefixChars = prefix.toCharArray();
TrieNode node = this.root;
for(char ch : prefixChars) {
int pos = ch - 'a';
if(node.son[pos] == null) {
return false;
}
node = node.son[pos];
}
return true;
}
} // Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");