前缀树(字典树)学习

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36783389/article/details/82932021

参考博客

https://blog.csdn.net/u013309870/article/details/71081393

https://blog.csdn.net/xudli/article/details/45840001

前缀树的结构

Trie树,又叫字典树、前缀树(Prefix Tree)、单词查找树或键树,是一种多叉树结构。如下图:

这里写图片描述
上图是一棵Trie树,表示了关键字集合{“a”, “to”, “tea”, “ted”, “ten”, “i”, “in”, “inn”} 。从上图可以归纳出Trie树的基本性质:
①根节点不包含字符,除根节点外的每一个子节点都包含一个字符。
②从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。
③每个节点的所有子节点包含的字符互不相同。
④从第一字符开始有连续重复的字符只占用一个节点,比如上面的to,和ten,中重复的单词t只占用了一个节点。

前缀树的应用

1、前缀匹配
2、字符串检索
3、词频统计
4、字符串排序

下面看看怎样使用前缀树来实现前缀匹配的。

前缀匹配

了解了前缀树的结构后,就可以利用前缀树的性质来解决现实中的问题。比如说查找一个字符串数组中是否含有前缀单词,什么是前缀单词:上面的 in,就是 inn 的前缀单词。如果有十几万条单词,并且每个单词的长度都是5-10以内,这样必定存在大量重复的字符,因此利用前缀树来求解不仅速度快而且空间复杂度也比较好。

参考题目

LeetCode 211 Add and Search Word - Data structure design

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.

这题很明显是字典树的应用

solution:

public class WordDictionary {
    private TrieNode root = new TrieNode();
 
    public void addWord(String word) {
        Map<Character, TrieNode> children = root.children;
        for(int i=0; i<word.length(); i++) {
            char c = word.charAt(i);
            TrieNode t;
            if(children.containsKey(c)) {
                t = children.get(c);
            } else {
                t = new TrieNode(c);
                children.put(c, t);
            }
            children = t.children;
            if(i==word.length()-1) t.leaf=true;
        }
    }
 
    public boolean search(String word) {
        return searchNode(word, root);
    }
    
    public boolean searchNode(String word, TrieNode tn) {
        if(tn==null) return false;
        if(word.length() == 0 ) return tn.leaf;
        
        Map<Character, TrieNode> children = tn.children;
        TrieNode t = null;
        char c = word.charAt(0);
        if(c=='.') {
            for(char key : children.keySet() ) {
                if(searchNode(word.substring(1), children.get(key) )) return true;
            }
            return false;
        } else if(!children.containsKey(c)) {
            return false;
        } else {
            t = children.get(c);
            return searchNode(word.substring(1), t);
        }
    }    
}
 
class TrieNode {
    // Initialize your data structure here.
    char c;
    boolean leaf;
    HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
    
    public TrieNode(char c) {
        this.c = c;
    }
        
    public TrieNode(){};
}

猜你喜欢

转载自blog.csdn.net/qq_36783389/article/details/82932021