insert
, search
, and startsWith
methods.Note:
You may assume that all inputs are consist of lowercase letters
a-z
.
---
Solution: The main thing here is really the data structure to store the trie. I found that using a map of character to TrieNode is sufficient to represent the structure. The other parts of the code only consist of single for loops.
class TrieNode {
// Initialize your data structure here.
Map<Character, TrieNode> children = new HashMap<>();
}
public class Trie {
private static final char TERMINAL = (char) -1;
private TrieNode root = new TrieNode();
// Inserts a word into the trie.
public void insert(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
TrieNode child = node.children.get(c);
if (child == null) {
child = new TrieNode();
node.children.put(c, child);
}
node = child;
}
node.children.put(TERMINAL, node);
}
private TrieNode searchPrefix(String prefix) {
TrieNode node = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
node = node.children.get(c);
if (node == null) return null;
}
return node;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode node = searchPrefix(word);
if (node == null) return false;
return node.children.containsKey(TERMINAL);
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode node = searchPrefix(prefix);
return (node != null);
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
No comments:
Post a Comment