trie树

字典树,顾名思义,像字典一样的树。


从上面的图中,我们或多或少的可以发现一些好玩的特性。
      第一:根节点不包含字符,除根节点外的每一个子节点都包含一个字符。
      第二:从根节点到某一节点,路径上经过的字符连接起来,就是该节点对应的字符串。
      第三:每个单词的公共前缀作为一个字符节点保存。
Tire树一般用来词频统计和前缀匹配。

现在以211. Add and Search Word - Data structure design为例来对字母树进行举例:https://leetcode.com/problems/add-and-search-word-data-structure-design/

这个树的难点在于数据结构的设计和添加字母。所以在设计的时候一定要明白根节点不包含字符,所以添加字母的时候我们都是以node->next进行访问的,而next是个数组,每个数组代表一个字母。这个也要注意!
删除的时候需要注意递归的变量:node,string和当前判断string的第几个字符。
如果不包含 '.'的判断,那么代码非常简单,因为回溯的条件就一个——当前字符不存在。而满足的条件也很简单——字符串访问结束,且字母树的end为true
有适配符的存在,就多了一个判断,因为适配符适配任何字母,所以对当前字母树的下一个节点以此进行搜索即可。

class TrieNode{
public:
    bool end;
    TrieNode* next[26];
    TrieNode(){
        memset(next,0,sizeof(next));
        end=false;
    }
};
class WordDictionary {
public:
    TrieNode *trRoot;
    // Adds a word into the data structure.
    void addWord(string word) {
        if(trRoot==NULL){
            trRoot=new TrieNode();
        }
        TrieNode* tmp=trRoot;
        for(int i=0;i<word.size();i++){
            if(tmp->next[word[i]-'a']==NULL){
                tmp->next[word[i]-'a']=new TrieNode();
            }
            if(i<word.size()-1){
                tmp=tmp->next[word[i]-'a'];
            }
            else{
                tmp->next[word[i]-'a']->end=true;
            }
        }
    }

    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    bool search(string word) {
        if(trRoot==NULL){
            trRoot=new TrieNode();
        }
        return dfs(trRoot,word,0);
    }
    
    bool dfs(TrieNode* node,string &word,int id){
        if(id==word.size()){
            if(node->end==true) return true;
            else return false;
        }
        if ('.' == word[id]) {
            for (int i = 0; i < 26; ++i) {
                if (node->next[i] && dfs(node->next[i], word, id + 1)) {
                    return true;
                }
            }
            return false;
        } 
        else{
            if(node->next[word[id]-'a']==NULL) return false;
            return dfs(node->next[word[id]-'a'],word,id+1);
        }
        return false;
    }
    
     WordDictionary() {
        trRoot = NULL;
    }
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值