Simple C++ using sorted Set


  • 0
    class Solution{
    public:
        string longestWord(vector<string>& words){
            auto cmp = [](const string& lhs, const string& rhs){
                if (lhs.size()==rhs.size()) return lhs > rhs;
                return lhs.size() < rhs.size();
            };
            set<string,decltype(cmp)> s(cmp);
            sort(words.begin(),words.end(),cmp);
            for (auto &&word: words){
                if (word.size()==1 || s.count(word.substr(0,word.size()-1))){
                    s.insert(word);
                }
            }
            return *max_element(s.begin(),s.end(),cmp);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.