词典中最长的单词
① 首先把n的字符串插入字典树
② 然后依次查询n的字符串是否满足要求——它的每个字符都是某个字符串的结尾。
class Solution {
string ans = "";
struct Node{
bool isEnd = false;
Node* children[26] = {0};
};
Node* root = new Node;
void insert(const string &s){
Node* p = root;
for(char c:s){
if(!p->children[c-'a']){
p->children[c-'a'] = new Node;
}
p = p->children[c-'a'];
}
p->isEnd = true;
}
bool find(const string &s){
Node* p = root;
for(char c:s){
if(!p->children[c-'a'] || !p->children[c-'a']->isEnd){
return false;
}
p = p->children[c-'a'];
}
return true;
}
public:
string longestWord(vector<string>& words) {
for(string &s:words){
insert(s);
}
for(string &s:words){
if(find(s)){
if(s.size()>ans.size()){
ans = s;
}else if(s.size()==ans.size()){
ans = min(ans,s);
}
}
}
return ans;
}
};