my clean c++ code


  • 0
    J
    class TriNode
    {  
    public:
    bool isWord;
    vector<TriNode*> child;
        TriNode()
        {
            child = vector<TriNode*>(26,NULL);
            isWord = false;
        }
    };
    
    
    class Trie {
    public:
        /** Initialize your data structure here. */
        Trie() {
            root = new TriNode();
        }
        
        /** Inserts a word into the trie. */
        void insert(string word) {
            TriNode *curr = root;
            for(int i = 0;i<word.size();i++)
            {
                if(curr->child[word[i]-'a']==NULL)
                   curr->child[word[i]-'a'] = new TriNode();
                curr = curr->child[word[i]-'a'];
            }
            curr->isWord = true;
        }
        
        /** Returns if the word is in the trie. */
        bool search(string word) {
            TriNode *curr = root;
            return dfs_search(word,0,curr);
        }    
    private:
        bool dfs_search(string word,int idx,TriNode *root)
        {
            if(!root)return false;
            if(idx==word.size()) 
            {
                if(root->isWord) return true;
                else return false;
            }
                
            if(word[idx] =='.')
            {
                for(int i = 0;i<26;i++)
                    if(root->child[i] && dfs_search(word,idx+1,root->child[i])) 
                        return true;  
            }
            else
            {
                 if(root->child[word[idx]-'a']==NULL)return false;
                 if(dfs_search(word,idx+1,root->child[word[idx]-'a'])) return true;
            }
            return false;   
        }
        
        TriNode *root;
        
    };
    
    
    class WordDictionary {
    public:
        /** Initialize your data structure here. */
        WordDictionary() {
              tree = new Trie();
        }
        
        /** Adds a word into the data structure. */
        void addWord(string word) {
               tree->insert(word);
        }
        
        /** 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) {
            return tree->search(word);
        }
    private:
        Trie *tree;
        
    };
    
    /**
     * Your WordDictionary object will be instantiated and called as such:
     * WordDictionary obj = new WordDictionary();
     * obj.addWord(word);
     * bool param_2 = obj.search(word);
     */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.