240
笔下虽有千言,胸中实无一策

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;
    }
};
posted @ 2020-09-30 13:26  CasperWin  阅读(76)  评论(0编辑  收藏  举报