今天看到一个比较好的数据结构,字典树,做一下记录,以供自己后期复习和读者朋友的参考。
1、定义
字典树又称单词查找树、前缀树、Trie树等,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
平衡树和哈希表也可以在字符串数据集中搜索单词,尽管哈希表可以在
O(1)的时间内寻找键值,但是无法做到以下操作:①找到具有用一前缀的全部键值;
②按照词典序枚举字符串的数据集;
③另外
Trie树相对于哈希表另一个优势是:随着哈希表大小的增加,会出现大量的哈希冲突,时间复杂度可能增加到O(n),其中n是插入的键的数量,与哈希表相比,Trie树在存储多个具有相同前缀的键时可以使用较少的空间,此外Trie树只需要O(m)的时间复杂度,其中m为键长,而在平衡树中查找键值需要O(mlogn)时间复杂度。
2、性质
①根节点不包含字符,除根节点外每一个节点都只包含一个字符;
② 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串;
③每个节点的所有子节点包含的字符都不相同。
3、基本操作
查找、插入和删除,当然删除操作比较少见。
4、实现方法
如搜索字典项目的方法为:
-
从根结点开始一次搜索;
-
取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;
-
在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。
-
迭代过程……
-
在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。
其他操作类似处理。
实现一个 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 构成的。
- 保证所有输入均为非空字符串。
class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root=new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node=root;
for(int i=0;i<word.length();i++){
int ch=word.charAt(i)-'a';
if(node.next[ch]==null){
node.next[ch]=new TrieNode();
}
node=node.next[ch];
}
node.isEnd=true;//加上一个标记,表示一个单词添加结束
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node=root;
for(int i=0;i<word.length();i++){
int ch=word.charAt(i)-'a';
if(node.next[ch]==null){
return false;
}
node=node.next[ch];
}
return node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node=root;
for(int i=0;i<prefix.length();i++){
int ch=prefix.charAt(i)-'a';
if(node.next[ch]==null){
return false;
}
node=node.next[ch];
}
return true;//直接返回true
}
class TrieNode{
private boolean isEnd;
private TrieNode []next;
public TrieNode(){
isEnd=false;
next=new TrieNode[26];
}
}
}
5、应用
①串的快速检索
给出N个单词组成的熟词表,以及一篇全用小写英文书写的文章,请你按最早出现的顺序写出所有不在熟词表中的生词。
在这道题中,我们可以用数组枚举,用哈希,用字典树,先把熟词建一棵树,然后读入文章进行比较,这种方法效率是比较高的。
②“串”排序
给定N个互不相同的仅由一个单词构成的英文名,让你将他们按字典序从小到大输出
用字典树进行排序,采用数组的方式创建字典树,这棵树的每个结点的所有儿子很显然地按照其字母大小排序。对这棵树进行先序遍历即可。
③最长公共前缀
对所有串建立字典树,对于两个串的最长公共前缀的长度即他们所在的结点的公共祖先个数,于是,问题就转化为当时公共祖先问题。
如:请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 WordDictionary:
WordDictionary()初始化词典对象void addWord(word)将word添加到数据结构中,之后可以对它进行匹配bool search(word)如果数据结构中存在字符串与word匹配,则返回true;否则,返回false。word中可能包含一些 ‘.’ ,每个 . 都可以表示任何一个字母。
示例:
输入:
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
输出:
[null,null,null,null,false,true,true,true]
解释:
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
提示:
1 <= word.length <= 500
addWord 中的 word 由小写英文字母组成
search 中的 word 由 '.' 或小写英文字母组成
最调用多 50000 次 addWord 和 search
代码如下:可以参照上述手写字典树的代码,仅仅当被匹配的字符串中有‘.’,需要做一个深度优先遍历。
class WordDictionary {
private TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
root=new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode node=root;
for(int i=0;i<word.length();i++){
int ch=word.charAt(i)-'a';
if(node.next[ch]==null){
node.next[ch]=new TrieNode();
}
node=node.next[ch];
}
node.isEnd=true;//加上一个标记,表示一个单词添加结束
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
TrieNode node=root;
return dfs(node,word,0);
}
public boolean dfs(TrieNode curr,String word,int id){
if(curr!=null){
//递归终止条件:
if(word.length()==id){
return curr.isEnd;
}
//分为字符中含有‘.’和不含有‘.’的情况:
if(word.charAt(id)=='.'){
for(TrieNode node:curr.next){
if(dfs(node,word,id+1)){
return true;
}
}
}else{
return dfs(curr.next[word.charAt(id)-'a'],word,id+1);
}
}
return false;
}
//单个字典树节点:
class TrieNode{
private boolean isEnd;
private TrieNode []next;
public TrieNode(){
isEnd=false;
next=new TrieNode[26];
}
}
}
1万+


并详解其应用&spm=1001.2101.3001.11974&articleId=109608461&d=1&t=3&u=507905074d014976b18c1c3bd25be11e)

被折叠的 条评论
为什么被折叠?



