2021/05/13
Leetcode:
- medium, 208.Implement Trie (Prefix Tree)
class Trie {
TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node = root;
for(char c : word.toCharArray()) {
int i = c - 'a';
if(node.children[i] == null)
node.children[i] = new TrieNode();
node = node.children[i];
}
node.word = word;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = root;
for(char c : word.toCharArray()) {
int i = c - 'a';
if(node.children[i] == null)
return false;
node = node.children[i];
}
return node.word != null;
}
class TrieNode {
String word;
TrieNode[] children = new TrieNode[26];
}
}
More: