forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Word in Dictionary.cpp
43 lines (39 loc) · 1.11 KB
/
Longest Word in Dictionary.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Runtime: 48 ms (Top 93.64%) | Memory: 30 MB (Top 50.94%)
struct node{
int end=0;
node* adj[26];
};
class Solution {
public:
string longestWord(vector<string>& words) {
auto root = new node();
auto insert = [&](string&s, int ind){
node* cur = root;
int i;
for(char&c:s){
i=c - 'a';
if(!cur->adj[i])cur->adj[i] = new node();
cur=cur->adj[i];
}
cur->end=ind;
};
int ind = 0;
for(string&s : words) insert(s,++ind);
stack<node*> st;
st.push(root);
string ans = "";
while(!st.empty()){
node* cur = st.top();st.pop();
if(cur->end>0 || cur==root){
if(cur!=root){
string word = words[cur->end-1];
if(word.size()>ans.size() ||
(word.size()==ans.size() && word<ans)){ans = word;}
}
for(int j=0;j<26;j++)
if(cur->adj[j])st.push(cur->adj[j]);
}
}
return ans;
}
};