实现说明
前缀树搜索与自动补全(Java)的核心是类 Trie、Node和函数 insert、suggest。
for (char ch : word.toCharArray()) { node = node.children.computeIfAbsent(ch, k -> new Node()); } 反复执行,循环体之外没有别的重复。管道就是一个 stream:数据源、惰性中间步骤、一个终端收集器。
常见问题
除了语言工具链还要下载什么吗?
除了这个语言的工具链,什么都不用再下载。 文件在加载时定义 insert、suggest。
主要签名是 public void insert(String word, int freq)
核心语句
return results.stream().limit(limit).map(r -> r[0]).toList();
for (char ch : prefix.toCharArray()) { node = node.children.get(ch); if (node == null) return List.of(); }
results.sort((a, b) -> Integer.compare(Integer.parseInt(b[1]), Integer.parseInt(a[1])));
代码示例
import java.util.*;
public class Trie {
static class Node { Map<Character, Node> children = new HashMap<>(); boolean isWord; int freq; }
Node root = new Node();
public void insert(String word, int freq) {
Node node = root;
for (char ch : word.toCharArray()) { node = node.children.computeIfAbsent(ch, k -> new Node()); }
node.isWord = true; node.freq += freq;
}
public List<String> suggest(String prefix, int limit) {
Node node = root;
for (char ch : prefix.toCharArray()) { node = node.children.get(ch); if (node == null) return List.of(); }
List<String[]> results = new ArrayList<>();
dfs(node, prefix, results);
results.sort((a, b) -> Integer.compare(Integer.parseInt(b[1]), Integer.parseInt(a[1])));
return results.stream().limit(limit).map(r -> r[0]).toList();
}
void dfs(Node n, String path, List<String[]> out) { if (n.isWord) out.add(new String[]{path, String.valueOf(n.freq)}); for (var e : n.children.entrySet()) dfs(e.getValue(), path + e.getKey(), out); }
}