如何实现一个基于 Trie 树的 Map 结构,以优化字符串键的存取效率?
import java.util.HashMap;
import java.util.Map;
public class TrieMap<T> {
private final TrieNode<T> root;
public TrieMap() {
this.root = new TrieNode<>();
}
// 插入键值对
public void put(String key, T value) {
TrieNode<T> node = root;
for (char c : key.toCharArray()) {
node.children.putIfAbsent(c, new TrieNode<>());
node = node.children.get(c);
}
node.value = value;
}
// 获取键对应的值
public T get(String key) {
TrieNode<T> node = root;
for (char c : key.toCharArray()) {
node = node.children.get(c);
if (node == null) {
return null;
}
}
return node.value;
}
// 检查键是否存在
public boolean containsKey(String key) {
return get(key) != null;
}
// 删除键
public void remove(String key) {
delete(root, key, 0);
}
private boolean delete(TrieNode<T> node, String key, int index) {
if (index == key.length()) {
node.value = null;
return node.children.isEmpty();
}
char c = key.charAt(index);
TrieNode<T> child = node.children.get(c);
if (child == null) {
return false;
}
boolean shouldDeleteChild = delete(child, key, index + 1);
if (shouldDeleteChild) {
node.children.remove(c);
return node.children.isEmpty();
}
return false;
}
private static class TrieNode<T> {
Map<Character, TrieNode<T>> children;
T value;
TrieNode() {
this.children = new HashMap<>();
this.value = null;
}
}
}
实现说明
-
TrieNode 结构:
- 使用
TrieNode类表示 Trie 树的节点,每个节点包含一个Map<Character, TrieNode<T>>,用于存储子节点。 value字段存储当前节点对应的值,若为null表示不是键的终点。
- 使用
-
插入操作(put):
- 遍历键的每个字符,从根节点开始逐层构建 Trie 树。
- 如果字符对应的子节点不存在,则创建新节点并插入。
- 遍历结束后,在终点节点设置对应的值。
- 示例:
TrieMap<Integer> map = new TrieMap<>(); map.put("apple", 1); // 插入键 "apple",值为 1
-
查询操作(get 和 containsKey):
- 从根节点开始,逐字符查找子节点。
- 如果中途找不到子节点,返回
null表示键不存在。 - 示例:
Integer value = map.get("apple"); // 返回 1 boolean exists = map.containsKey("apple"); // 返回 true
-
删除操作(remove):
- 递归删除键的每个字符节点,如果节点不再被其他键共享,则将其从父节点中移除。
- 示例:
map.remove("apple"); // 删除键 "apple"
优化细节
- 时间复杂度:插入、查询和删除的时间复杂度均为 O(L),其中 L 是键的长度,与键的数量无关。
- 空间优化:通过共享前缀节点,Trie 树显著减少了字符串键的存储开销,适合大量重复前缀的场景。
适用场景
- 适合存储大量字符串键的字典结构。
- 常见于搜索引擎的自动补全、拼写检查等功能中。
示例扩展
TrieMap<String> dictionary = new TrieMap<>();
dictionary.put("hello", "greeting");
dictionary.put("hell", "inferno");
System.out.println(dictionary.get("hello")); // 输出 "greeting"
System.out.println(dictionary.get("hell")); // 输出 "inferno"
dictionary.remove("hello");
System.out.println(dictionary.containsKey("hello")); // 输出 false