题目
Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
答案
class Trie {
class TrieNode {
// Initialize your data structure here.
public TrieNode() {
children = new TrieNode[26];
bLeaf = false;
}
int value;
boolean bLeaf;
TrieNode[] children;
}
private boolean charExist(char c, TrieNode curr) {
return curr.children[c - 'a'] != null;
}
private TrieNode nextNode(char c, TrieNode curr) {
return curr.children[c - 'a'];
}
private void insertChar(char c, TrieNode curr, TrieNode ins) {
curr.children[c - 'a'] = ins;
}
TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode curr = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(!charExist(c, curr)) {
TrieNode newnode = new TrieNode();
newnode.value = c;
insertChar(c, curr, newnode);
}
// You will need to mark this node as leaf, even if it is not really a leaf in the tree
// but it is a leaf for this particular string word
curr = nextNode(c, curr);
if(i == word.length() - 1)
curr.bLeaf = true;
}
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode curr = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(charExist(c, curr))
curr = nextNode(c, curr);
else
return false;
}
return curr.bLeaf;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode curr = root;
for(int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if(charExist(c, curr))
curr = nextNode(c, curr);
else
return false;
}
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);
*/