208. Implement Trie (Prefix Tree)
Problem
A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
- Trie() Initializes the trie object.
- void insert(String word) Inserts the string word into the trie.
- boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
- boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
Example 1:
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return True
Constraints:
- 1 <= word.length, prefix.length <= 2000
- word and prefix consist only of lowercase English letters.
- At most
calls in total will be made to insert, search, and startsWith.
Code
class Trie {
class TrieNode {
TrieNode[] children;
boolean isWord;
String word;
public TrieNode(){
children = new TrieNode[26];
isWord = false;
word = "";
}
}
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for(int i = 0; i < word.length(); i++){
int index = word.charAt(i) - 'a';
if(node.children[index] == null){
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.isWord = true;
}
public boolean search(String word) {
TrieNode node = root;
for(int i = 0; i < word.length(); i++){
int index = word.charAt(i) - 'a';
if(node.children[index] == null) return false;
node = node.children[index];
}
return node.isWord;
}
public boolean startsWith(String prefix) {
TrieNode node = root;
for(int i = 0; i < prefix.length(); i++){
int index = prefix.charAt(i) - 'a';
if(node.children[index] == null) return false;
node = node.children[index];
}
return true;
}
}
how to save trie to db
- Persistent storage
- Two options
- Document store - like MongoDB
- Serialize trie
- key-value store
- A trie can be represented in a hash table form
- Every prefix in the trie is mapped to a value in a hash table
- Data on each trie node is mapped to a value in a hash table
- Document store - like MongoDB
按 <- 键看上一题!
207. Course Schedule
按 -> 键看下一题!
209. Minimum Size Subarray Sum