208. Implement Trie (Prefix Tree) & 211. Add and Search Word
class TrieNode {
public TrieNode[] children;
public boolean end;
public TrieNode() {
this.children = new TrieNode[26];
}
}
public class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
this.root = new TrieNode();
root.end = true;
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode tn = root;
for (char c : word.toCharArray()) {
if (tn.children[c - 'a'] == null) tn.children[c - 'a'] = new TrieNode();
tn = tn.children[c - 'a']; //set tn to be the current tn's child
}
tn.end = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode tn = root;
for (char c : word.toCharArray()) {
if (tn.children[c - 'a'] == null) return false;
tn = tn.children[c - 'a'];
}
return tn.end; //确定这个单词存在,而不是其他单词的一部分
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode tn = root;
for (char c : prefix.toCharArray()) {
if (tn.children[c - 'a'] == null) return false;
tn = tn.children[c - '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);
*/Last updated