C++ sort by word length

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

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jimmy Shen

Jimmy Shen

Data Scientist/MLE/SWE @takemobi