• LeetCode 208. Implement Trie (Prefix Tree)


    题目

    题意:实现一个前缀树

    class Trie {
    public:
        int map[100005][126];
        int tag[100005][126];
        int num;
        /** Initialize your data structure here. */
        Trie() {
            
            memset(map,0,sizeof(map));
            memset(tag,0,sizeof(tag));
            num=0;
            
            
        }
        
        /** Inserts a word into the trie. */
        void insert(string word) {
            
            Add(word,0,0);
            
        }
        
        void Add(string word,int i,int pos)
        {
            if(i==word.length())
            {
                return;
            }
                
            if(map[pos][word[i]]==0)
            {
                map[pos][word[i]]=++num;
            }
            
            if(i==word.length()-1)
            {
                tag[pos][word[i]]=1;
            }
            
            Add(word,i+1,map[pos][word[i]]);
        }
        
        
        
        /** Returns if the word is in the trie. */
        bool search(string word) {
            
           return SearchWord(word,0,0,1);
            
        }
        
        bool SearchWord(string word,int i,int pos,int t)
        {
            if(i==word.length())
                return false;
           
            if(map[pos][word[i]]==0)
            {
                return false;
            }
            else
            {
                if(i==word.length()-1)
                {
                    if(t==1&&tag[pos][word[i]]==1)
                        return true;
                    if(t==0)
                        return true;
                }
                
                return SearchWord(word,i+1,map[pos][word[i]],t);
            }
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            return SearchWord(prefix,0,0,0);
        }
    };
    
    /**
     * Your Trie object will be instantiated and called as such:
     * Trie* obj = new Trie();
     * obj->insert(word);
     * bool param_2 = obj->search(word);
     * bool param_3 = obj->startsWith(prefix);
     */
    
  • 相关阅读:
    【258】雅思口语常用话
    【256】◀▶IEW-答案
    UITabBarController 标签栏控制器
    枚举
    HDU3631:Shortest Path(Floyd)
    让Barebox正确引导Tiny6410的linux内核
    调度子系统2_核心调度器
    12.10 公司面试总结
    X265编译中C2220错误的解决办法
    JSP元素和标签
  • 原文地址:https://www.cnblogs.com/dacc123/p/12306348.html
Copyright © 2020-2023  润新知