Longest Word in Dictionary

2018/1/22 posted in  leetcode

class Solution {
public:
    string longestWord(vector<string>& words) {
        sort(words.begin(), words.end());  //对字符串排好序,按照字符的ascll编码,匹配字典的排序
        unordered_set<string> set;
        string res = "";
        for (int i = 0 ; i<words.size(); i++) {
            if (words[i].size()==1||set.count(words[i].substr(0,words[i].size()-1))) {
                res = words[i].size()>res.size() ? words[i]:res;
                set.insert(words[i]);
            }
        }

        return res;
    }
};