参考链接
实现
import java.util.HashMap;
import java.util.Map;
/**
* 字典树, 以实现基本的增删查操作
*/
public class Trie {
/**
* 根结点
*/
private Node root;
/**
* 单词数量
*/
private int size;
public Trie() {
root = new Node();
}
/**
* 添加单词
*
* @param word 单词
*/
public void add(String word) {
Node p = root;
for (char ch : word.toCharArray()) {
if (p.next.get(ch) == null) {
p.next.put(ch, new Node());
}
p = p.next.get(ch);
}
// 该节点上没有单词则加上单词
// 防止相同单词重复添加
if (!p.isWord) {
p.isWord = true;
++size;
}
}
/**
* 查询单词
*
* @param word 单词
* @return 是否存在于Trie中
*/
public boolean contains(String word) {
Node p = root;
for (char ch : word.toCharArray()) {
p = p.next.get(ch);
if (p == null) {
return false;
}
}
return p.isWord;
}
/**
* 删除一个单词
*
* @param word 单词
* @return 是否删除成功
*/
public boolean delete(String word) {
Node p = root;
for (char ch : word.toCharArray()) {
p = p.next.get(ch);
if (p == null) {
return false;
}
}
if (p.isWord) {
--size;
p.isWord = false;
if (p.next.size() == 0) {
p.next = null;
p = null;
}
return true;
} else {
return false;
}
}
}
/**
* 字符结点
*/
class Node {
/**
* 当前结点是否为某个单词的结尾
*/
public boolean isWord;
/**
* 用Map存储子结点
*/
public Map<Character, Node> next;
public Node() {
next = new HashMap<>();
}
public Node(boolean isWord) {
this.isWord = isWord;
}
}
class Main {
public static void main(String[] args) {
Trie trie = new Trie();
trie.add("hello");
trie.add("app");
trie.add("test");
System.out.println(trie.contains("test"));
System.out.println(trie.contains("tes"));
System.out.println(trie.delete("test"));
System.out.println(trie.contains("test"));
}
}