非常巧妙的方法:
class Solution {
public:
string longestWord(vector<string>& words) {
unordered_set<string> hash;
sort(words.begin(),words.end());
string res;
for(auto word:words){
if(word.size() == 1 ||
hash.count(word.substr(0,word.size()-1))){
hash.insert(word);
res = (word.size() > res.size())? word:res;
}
}
return res;
}
};
运行效率:
Runtime: 48 ms, faster than 83.47% of C++ online submissions for Longest Word in Dictionary.
Memory Usage: 18.7 MB, less than 76.12% of C++ online submissions for Longest Word in Dictionary.