C++ sort by word length

From [1]

std::vector<std::string> v;
std::sort(v.begin(), v.end(), []
(const std::string& first, const std::string& second){
return first.size() < second.size();
});

An application is here

Longest Prefix Sequence

int solve(vector<string>& words) {
sort(words.begin(), words.end(), [](string &a, string &b){
return a.size() < b.size();});
int ret = 0;
unordered_map<string, int> memo;
for (auto word: words) {
if (word.size() > 1) {
memo[word] = 1;
string subword = word.substr(0,word.size() - 1);
if (memo.find(subword) != memo.end()){
memo[word] = max(memo[word], memo[subword] + 1);
}
} else {
memo[word] = 1;
}
}
for (auto [k, v]: memo) ret = max(ret, v);
return ret;
}

Reference

[1] https://stackoverflow.com/questions/18831470/sorting-a-string-vector-based-on-the-string-size

--

--