30 Day Challenge Day 15 | Leetcode 720. Longest Word in Dictionary
题解
Easy
方法一:Greedy 贪心算法
class Solution {
public:
string longestWord(vector<string>& words) {
string res;
unordered_set<string> s;
sort(words.begin(), words.end());
for(auto& word : words) {
if(word.size() == 1 || s.count(word.substr(0, word.size()-1))) {
res = word.size() > res.size() ? word : res;
s.insert(word);
}
}
return res;
}
};