詞典中最長的單詞
① 首先把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;
}
};