Implement a trie with insert
, search
,
and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
Have you met this question in a real interview?
思路: Each TrieNode has a children with 26 TrieNode. When we want to insert or search a word from a TrieTree, we need to traverse the tree from root to leaf.
class TrieNode {
// Initialize your data structure here.
public char val;
public TrieNode[] children = new TrieNode[26];
public boolean isWord = false;
public TrieNode() {
}
public TrieNode(char c){
TrieNode node = new TrieNode();
node.val = c;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
root.val = ' ';
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode curNode = root;
for(int i = 0; i < word.length(); i++){
if(curNode.children[word.charAt(i) - 'a'] == null){
//curNode.children[word.charAt(i) - 'a'] = new TrieNode();
curNode.children[word.charAt(i) - 'a'] = new TrieNode(word.charAt(i));
}
curNode = curNode.children[word.charAt(i) - 'a'];
}
curNode.isWord = true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode curNode = root;
for(int i = 0; i < word.length(); i++){
if(curNode.children[word.charAt(i) - 'a'] == null)
return false;
curNode = curNode.children[word.charAt(i) - 'a'];
}
return curNode.isWord;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode curNode = root;
for(int i = 0; i < prefix.length(); i++){
if(curNode.children[prefix.charAt(i) - 'a'] == null)
return false;
curNode = curNode.children[prefix.charAt(i) - 'a'];
}
return true;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");