字典树(Trie)是一种可以高效存储与查询字符串的数据结构,在字典树上每个边是一个字符,子结点比父结点多了一个其边上的字符。
一个字典树如上图所示,这个字典树中存了单词:at, tea, ten, to。
java代码实现:
import java.util.*;
public class Trie {
private static class Node {
String word = null;
Map<Character, Node> children = new HashMap<>();
}
private Node root = new Node();
public void add(String s) {
Node current = root;
for (int i = 0, len = s.length(); i < len; i++) {
char c = s.charAt(i);
if (!current.children.containsKey(c)) {
current.children.put(c, new Node());
}
current = current.children.get(c);
}
current.word = s;
}
public boolean contains(String s) {
Node current = root;
for (int i = 0, len = s.length(); i < len; i++) {
char c = s.charAt(i);
if (current.children.containsKey(c)) {
current = current.children.get(c);
} else {
return false;
}
}
return current.word != null;
}
public List<String> getAll() {
List<String> all = new ArrayList<>();
List<Node> stack = new ArrayList<>();
stack.add(root);
while (!stack.isEmpty()) {
Node current = stack.remove(stack.size() - 1);
stack.addAll(current.children.values());
if (current.word != null) all.add(current.word);
}
return all;
}
}