题目描述
解法:打表
我们先把 words 按照单词长度进行排序,长度相同的按照题目要求按照字典序进行排序,最终 words 能保证我们在遍历的过程中可以每一步都是当前最长、字典序最小的单词
如果当前遍历到的单词删除最后一个字母在表中可以查找到,那么说明当前这个单词是符合题目答案的要求,那么就可以更新答案,将其插入到表中
class Solution {
public:
string longestWord(vector<string>& words) {
sort(words.begin(), words.end(), [](const string& a, const string& b){
return a.size() != b.size() ? a.size() < b.size() : a>b;
});
string ans;
unordered_set<string> candidates = {""};
for (auto word: words)
{
if (candidates.count(word.substr(0, word.size() - 1)))
{
candidates.emplace(word);
ans = word;
}
}
return ans;
}
};
解法二:字典树
这道题在字典树的基础上修改一下 search
方法就可以得到:起始时,我们将所有的 word 插入到字典树中,那么每个符合题目要求的候选答案其前缀结点必定满足 isEnd = true,接下来比较长度和字典序得到最长的词即可
class Trie {
private:
bool isEnd;
Trie* next[26];
public:
/** Initialize your data structure here. */
Trie() {
isEnd = false;
memset(next, 0, sizeof(next));
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie* node = this;
for(auto c: word)
{
if(node->next[c-'a']==NULL) node->next[c-'a'] = new Trie();
node = node->next[c-'a'];
}
node->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* node = this;
for(auto c: word)
{
node = node->next[c-'a'];
if(node==NULL || !node->isEnd) return false;
}
return node->isEnd;
}
};
class Solution {
public:
string longestWord(vector<string>& words) {
Trie trie;
for (auto word: words) trie.insert(word);
string ans = "";
for (auto word: words)
{
if(trie.search(word))
if (word.size() > ans.size() || (word.size() == ans.size() && word <ans))
ans = word;
}
return ans;
}
};