其他分享
首页 > 其他分享> > [LC 676] Trie树简单运用

[LC 676] Trie树简单运用

作者:互联网

https://leetcode.cn/problems/implement-magic-dictionary/

static int son[10010][26];
int idx = 0;
static int cnt[10010];
class MagicDictionary {
public:
    //Trie树相关的数据;
    MagicDictionary() {
        memset(son, 0, sizeof son);
        memset(cnt, 0, sizeof cnt);
        idx = 0;
    }

    void insert(string& str)
    {
        int p = 0;
        for (int i = 0; i < str.size(); i++)
        {
            int u = str[i] - 'a';
            if (!son[p][u]) son[p][u] = ++idx;
            p = son[p][u];
        }

        cnt[p]++; //标记字符串结尾;
    }

    void buildDict(vector<string> dictionary) {
        for (auto str : dictionary)
        {
            insert(str);
        }
    }
    
    bool search(string searchWord) {
        return query(searchWord);
    }

    bool query(string & str)
    {
        int nums = 0; //表示在当前Trie树搜索中对应的不同字母个数;
        int p = 0; //进行dfs遍历查找;
        return dfs(str, p,  nums, 0);
    }

    bool dfs(string& str, int p, int nums, int idx)
    {
        if (idx == str.size())
        {
            if (nums == 1 && cnt[p])
                return true; 
            return false;
        }

        //遍历该Trie树上所有分支;
        for (int i = 0; i < 26; i++)
        {
            if (!son[p][i]) continue;
            if (dfs(str, son[p][i], nums + ((str[idx] - 'a') != i) ,idx+1)) return true;
        }
        return false;
    }
};

/**
 * Your MagicDictionary object will be instantiated and called as such:
 * MagicDictionary* obj = new MagicDictionary();
 * obj->buildDict(dictionary);
 * bool param_2 = obj->search(searchWord);
 */

标签:return,LC,idx,nums,Trie,676,son,int,str
来源: https://www.cnblogs.com/zhanghanLeo/p/16460575.html