Pass in Run code, but fail in submit


  • 0
    B

    Anyone can help me with my code? My code can successfully get the correct answer in the runcode mode, but fail in the submit. Any advice or discussion will be appreciated.

    class Solution {
    public:
        struct TrieNode{
            string leaves;
            vector<TrieNode*> children;
            vector<string> startWith;
            TrieNode(){
                children.assign(26, nullptr);
            }
        };
        
        void add(TrieNode* root, string& word){
            TrieNode* p = root;
            for(char c: word){
                if(!p->children[c-'a']){
                    p->children[c-'a'] = new TrieNode();
                }
                p = p->children[c-'a'];
                p->startWith.push_back(word);
            }
            p->leaves = word;
        }
        
        vector<string> search(TrieNode* root, string prefix){
            vector<string> words;
            TrieNode* p = root;
            int i = 0;
            for(; i < prefix.size(); i++){
                if(p->children[prefix[i]-'a'])
                    p = p->children[prefix[i]-'a'];
                else
                    return words;
            }
            return p->startWith;
        }
        
        void helper(vector<string>& cur, TrieNode* root, vector<vector<string>>& res){
            if(cur.size() == cur[0].size()){
                res.push_back(cur);
            }
            int len = cur.size();
            string prefix = "";
            for(int i=0; i<len; i++){
                prefix.push_back(cur[i][len]);
            }
            vector<string> preWords = search(root, prefix);
            
            for(auto preWord: preWords){
                cur.push_back(preWord);
                helper(cur, root, res);
                cur.pop_back();
            }
        }
        
        vector<vector<string>> wordSquares(vector<string>& words) {
            TrieNode* root = new TrieNode();
            for(auto& word: words){
                add(root, word);
            }
            
            vector<vector<string>> res;
            for(auto str: words){
                vector<string> cur = {str};
                helper(cur, root, res);
            }
            return res;
        }
    };
    

Log in to reply
 

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