720. Longest Word in Dictionary (DFS + Trie --- Unfinished. TLE. Too much work to make it right...)

class TrieNode { public: TrieNode(): is_word(false), children(26, nullptr) {} bool is_word; vector<TrieNode*> children; }; class Trie { public: Trie() { root = new TrieNode(); // construct a new TrieNode for root... } bool search(const string & word){ TrieNode * ptr = root; if (ptr->children.empty()) return false; for (char c: word){ size_t pos = c - 'a'; if (!ptr->children[pos]) return false; else ptr = ptr->children[pos]; } return ptr->is_word; } void insert(const string & word){ TrieNode * ptr = root; for (char c : word){ size_t pos = c - 'a'; if (!ptr->children[pos]) ptr->children[pos] = new TrieNode(); ptr = ptr->children[pos]; } ptr->is_word = true; } private: TrieNode * root; }; class Solution { public: string longestWord(vector<string>& words) { Trie * hey = new Trie(); // populate the trie for (string word : words) hey->insert(word); vector<string> ans; for (string word : words){ string copy = word; bool all_found = true; while(!copy.empty()){ if (hey->search(copy) == false) all_found = false; else copy.pop_back(); } if (all_found) ans.push_back(word); } string final_ans; int length = 0; for (string a: ans){ if (a.size() > length || (a.size() == length && a > final_ans)) final_ans = a; } return final_ans; } };
To be continued.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.