Trie
Trie树,又称字典树,单词查找树或者前缀树,是一种用于快速检索的多叉树结构,如英文字母的字典树是一个26叉树,数字的字典树是一个10叉树。Trie树的基本性质可以归纳为:
(1)根节点不包含字符,除根节点之外每个节点只包含一个字符。
(2)从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。
(3)每个节点的所有子节点包含的字符串不相同。
实现一个 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 构成的。
- 保证所有输入均为非空字符串。
题解:比较简单的做法是每个节点都设置一个大小26的数组,用来表示26个字母
public class Trie {
//前缀树的节点
private class Node {
//每个节点包含26个字母
Node[] childs = new Node[26];
//是否为叶子节点的标志
boolean isLeaf;
}
//根节点为空节点
private Node root = new Node();
public Trie() {}
public void insert(String word) {
if (word == null) {
return;
}
//从根节点出发,迭代添加
Node pre = root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
//如果当前字符没有添加,就新建
if (pre.childs[index] == null) {
pre.childs[index] = new Node();
}
//更新pre
pre = pre.childs[index];
}
//添加完之后,将isLeaf置为true,标识存储完了
pre.isLeaf = true;
}
public boolean search(String word) {
if (word == null) {
return false;
}
//从根节点开始查找
Node pre = root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
//如果遇到一处没有,就返回false
if (pre.childs[index] == null) {
return false;
}
//更新pre
pre = pre.childs[index];
}
//返回最后一个字符的isLeaf
return pre.isLeaf;
}
public boolean startsWith(String word) {
if (word == null) {
return false;
}
//从根节点开始查找
Node pre = root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
//如果遇到一处没有,就返回false
if (pre.childs[index] == null) {
return false;
}
//更新pre
pre = pre.childs[index];
}
return true;
}
}
原文:学就完事了