Longest Word in Dictionary LeetCode solution in C++
1struct node {2int end = 0;3node *adj[26];4};56class Solution {7public:8string longestWord(vector<string> &words) {9auto root = new node();10auto insert = [&](string &s, int ind) {11node *cur = root;12int i;13for (char &c : s) {14i = c - 'a';15if (!cur->adj[i]) cur->adj[i] = new node();16cur = cur->adj[i];17}18cur->end = ind;19};2021int ind = 0;22for (string &s : words) insert(s, ++ind);2324stack<node *> st;25st.push(root);26string ans = "";27while (!st.empty()) {28node *cur = st.top();29st.pop();30if (cur->end > 0 || cur == root) {31if (cur != root) {32string word = words[cur->end - 1];33if (word.size() > ans.size() || (word.size() == ans.size() && word < ans)) {34ans = word;35}36}3738for (int j = 0; j < 26; j++)39if (cur->adj[j]) st.push(cur->adj[j]);40}41}42return ans;43}44};