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.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
1 <= word.length, prefix.length <= 2000
word
and prefix
consist only of lowercase English letters.3 * 10^4
calls in total will be made to insert
, search
, and startsWith
.기본적인 트라이를 생성하고, 삽입, 검색, 접두사 찾기를 만드는 문제이다.
우선 트라이와 트라이 안에 들어갈 노드 클래스를 만들어준다.
여기서는 앞부분만 같으면 뒷부분은 상관없기 때문에 flag만 true로 나오면 찾은 것이고, false라면 해당되는 단어가 없다는 뜻이라 search랑 비슷하나 조금은 다르다.
class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
Map<Character, TrieNode> children = root.getChildren();
for (int i = 0; i < word.length(); i++) {
char curLetter = word.charAt(i);
TrieNode node;
if (children.containsKey(curLetter)) {
node = children.get(curLetter);
} else {
node = new TrieNode();
children.put(curLetter, node);
}
children = node.getChildren();
if (i == word.length() - 1) {
node.setEnd();
}
}
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Map<Character, TrieNode> children = root.getChildren();
boolean flag = true;
TrieNode node = null;
for (int i = 0; i < word.length(); i++) {
char curLetter = word.charAt(i);
if (children.containsKey(curLetter)) {
node = children.get(curLetter);
children = node.getChildren();
} else {
flag = false;
break;
}
}
return flag && node.isEnd();
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Map<Character, TrieNode> children = root.getChildren();
boolean flag = true;
TrieNode node;
for(int i = 0; i < prefix.length(); i++) {
char curLetter = prefix.charAt(i);
if (children.containsKey(curLetter)) {
node = children.get(curLetter);
children = node.getChildren();
} else {
flag = false;
break;
}
}
return flag;
}
}
class TrieNode {
private Map<Character, TrieNode> children;
private boolean isEnd;
public TrieNode() {
children = new HashMap<>();
}
public Map<Character, TrieNode> getChildren() {
return this.children;
}
public void setEnd() {
this.isEnd = true;
}
public boolean isEnd() {
return this.isEnd;
}
}
/**
* 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);
*/