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

--

--

--

Data Scientist/MLE/SWE @takemobi

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why I Chose to Pursue CS and Programming

5 tips on how to pass ITIL 4 Foundation Exam

Yumi Report no. 3: April 25 — May 7

A Scaling Approach to Digital Transformation

File System Traversal with Ruby

Kotlin Static Analysis — why and how?

Redis — Installation and Explanation with Examples

Building a Basic Authorization Server Using Resource Owner Password Credentials Flow

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

More from Medium

My journey from the world of Java and Python to C++

Tail Recursion in Python

LC | Weekly Contest 281 | Q4 2183. Count Array Pairs Divisible by K | Hard

The Python/C++ Debate