208. Implement Trie (Prefix Tree)
https://leetcode.com/problems/implement-trie-prefix-tree/
class Trie {
class Node {
boolean is_word;
Map<Character, Node> map;
Node() {
map = new HashMap<>();
is_word = false;
}
}
Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
char[] arr = word.toCharArray();
Node cur = root;
for (char ch : arr) {
Node next = cur.map.get(ch);
if (next == null) {
next = new Node();
cur.map.put(ch, next);
}
cur = next;
}
cur.is_word = true;
}
public boolean search(String word) {
char[] arr = word.toCharArray();
Node cur = root;
for (char ch : arr) {
Node next = cur.map.get(ch);
if (next == null) {
return false;
}
cur = next;
}
return cur.is_word;
}
public boolean startsWith(String prefix) {
char[] arr = prefix.toCharArray();
Node cur = root;
for (char ch : arr) {
Node next = cur.map.get(ch);
if (next == null) {
return false;
}
cur = next;
}
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