What is wrong with my code?


  • 0
    F
    class WordDictionary {
    private:
        class TrieNode{
        public:
            TrieNode * nodes[26] = {0};
            bool end = false;
            TrieNode(){
                
            }
        };
        TrieNode * root;
    public:
        WordDictionary(){
            root = new TrieNode();
        }
        
        // Adds a word into the data structure.
        void addWord(string word) {
            TrieNode * curr = root;
            for(auto c : word){
                if(!curr->nodes[c-'a']){
                    curr->nodes[c-'a'] = new TrieNode();
                }
                
                curr = curr->nodes[c-'a'];
            }
            
            curr->end = true;
        }
        
        bool dfs(string & word, int index, TrieNode * curr){
            if(index == word.size()){
                return curr->end;
            }
        
            if(word[index] != '.'){
                if(curr->nodes[word[index]-'a']){
                    return dfs(word,index+1,curr->nodes[word[index]-'a']);
                }else{
                    return false;
                }
            }else{
                for(char i = 'a'; i <= 'z'; i++){
                    word[index] = i;
                    if(curr->nodes[word[index]-'a'] && dfs(word,index+1,curr->nodes[word[index]-'a'])){
                        return true;
                    }
                }
                return false;
            }
        }
        
        // 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 dfs(word,0,root);    
        }
    };
    
    // Your WordDictionary object will be instantiated and called as such:
    // WordDictionary wordDictionary;
    // wordDictionary.addWord("word");
    // wordDictionary.search("pattern");
    

    the above code fails the tests but when I change

    for(char i = 'a'; i <= 'z'; i++){
                    word[index] = i;
                    if(curr->nodes[word[index]-'a'] && dfs(word,index+1,curr->nodes[word[index]-'a'])){
                        return true;
                    }
                }
    

    to

    for(int i = 0 ; i < 26; i++){
                    if(curr->nodes[i] && dfs(word,index+1,curr->nodes[i])){
                        return true;
                    }
                }
    

    somehow it works, isn't the above 2 codes pretty much the same thing?


Log in to reply
 

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