cout for final result gives correct value, but the function shows return value on testing as empty


  • 0
    S

    const int mx = 26;
    class Solution {
    struct TrieNode {
    char val;
    vector<TrieNode*> children;
    bool isEnd;
    TrieNode() {
    isEnd = false;
    children.clear();
    children.resize(26, nullptr);
    }
    TrieNode(char _val) {
    val = _val;
    isEnd = false;
    children.clear();
    children.resize(26, nullptr);
    }
    };

    struct Trie {
    private:
    TrieNode *root;
    int getVal(const char ch) {
    return ch - 'a';
    }

        void update(string &res, string cur) {
            cout << cur << " " << res << endl;
            if (cur.size() > res.size()) {
                res = cur;
            } else if (res.size() == cur.size()) {
                res = min(res, cur);
            }
            return;
        }
        void search(TrieNode *node, string &cur, string &res) {
            if (!node || !node->isEnd) {
                         //   cout << cur << " " << res << endl;
    
                if (cur.size() > res.size()) {
                    res = cur;
                } else if (res.size() == cur.size()) {
                    res = min(res, cur);
                }
               // if (cur != "") {
                    // update(res, cur);
               // }
                return;
            }
            cur.push_back(node->val);
            
            for (int i = 0; i < node->children.size(); i++) {
                search(node->children[i], cur, res);
            }
            cur.pop_back();
        }
    
    public:
        string result;
        Trie() {
            this->root = new TrieNode();
            this->root->isEnd = true;
        }
    
        void insert(const string &s) {
            TrieNode *node = root;
            for (int i = 0; i < s.size(); i++) {
                if (!node->children[s[i] - 'a']) {
                    node->children[s[i] - 'a'] = new TrieNode(s[i]);
                }
                node = node->children[s[i] - 'a'];
    
            }
            
            node->isEnd = true;
            cout << endl;
        }
    
        string search() {
            static string res = "";
            string cur = "";
            if(!root)
            {
                cout << "root null \n";
            }
            search(root, cur, res);
            cout << "res is : " << res << endl;
            result = res;
            return res;
        }
    

    };

    public:
    string longestWord(vector<string>& words) {
    Trie *trie = new Trie();
    for (int i = 0; i < words.size(); i++) {
    trie->insert(words[i]);
    }
    cout << "insert completed" << endl;
    string ret = (trie->search());
    cout << ret << " " << trie->result << endl;
    return ret;
    }
    };


Log in to reply
 

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