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.
实现一个trie树
class Trie {
class Node {
Node[] next = new Node[27];
}
Node endNode = new Node();
Node root = new Node();
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node curNode = root;
for (char c : word.toCharArray()) {
if (curNode.next[c - 'a'] == null) {
curNode.next[c - 'a'] = new Node();
}
curNode = curNode.next[c - 'a'];
}
curNode.next[26] = endNode;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
return search(word, true);
}
public boolean search(String word, boolean mustEnd) {
Node curNode = root;
for (char c : word.toCharArray()) {
if (curNode.next[c - 'a'] == null) return false;
curNode = curNode.next[c - 'a'];
}
return mustEnd ? curNode.next[26] != null : true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return search(prefix, false);
}
}