Medium | LeetCode 208. 实现 Trie (前缀树) | 设计
208. 实现 Trie (前缀树)
实现一个 Trie (前缀树),包含 insert
, search
, 和 startsWith
这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
-
你可以假设所有的输入都是由小写字母
a-z
构成的。 -
保证所有输入均为非空字符串。
解题思路
class Trie {
class TrieNode {
private Map<Character, TrieNode> children = new HashMap<>();
private String word = null;
public TrieNode addChildren(Character ch) {
TrieNode newNode = new TrieNode();
children.put(ch, newNode);
return newNode;
}
public void setWord(String word) {
if (this.word != null) {
return;
}
this.word = word;
}
public boolean hasChild(Character child) {
return children.containsKey(child);
}
public TrieNode getChild(Character child) {
return children.get(child);
}
}
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
this.root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode p = root;
for (Character ch : word.toCharArray()) {
if (!p.hasChild(ch)) {
p = p.addChildren(ch);
} else {
p = p.getChild(ch);
}
}
p.setWord(word);
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode p = root;
for (Character ch : word.toCharArray()) {
if (p.hasChild(ch)) {
p = p.getChild(ch);
} else {
return false;
}
}
return p.word != null;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode p = root;
for (Character ch : prefix.toCharArray()) {
if (p.hasChild(ch)) {
p = p.getChild(ch);
} else {
return false;
}
}
return true;
}
}