Skip to content

Commit 7e25337

Browse files
authored
Create longest-string-chain.cpp
1 parent 5291eac commit 7e25337

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

C++/longest-string-chain.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time: O(n * l^2)
2+
// Space: O(n * l)
3+
4+
class Solution {
5+
public:
6+
int longestStrChain(vector<string>& words) {
7+
sort(words.begin(), words.end(),
8+
[](const string& a, const string& b) {
9+
return less<int>()(a.length(), b.length());
10+
});
11+
unordered_map<string, int> dp;
12+
for (const auto& w : words) {
13+
for (int i = 0; i < w.length(); ++i) {
14+
auto tmp = w.substr(0, i);
15+
tmp += w.substr(i + 1);
16+
dp[w] = max(dp[w], dp[tmp] + 1);
17+
}
18+
}
19+
using pair_type = decltype(dp)::value_type;
20+
return max_element(dp.cbegin(), dp.cend(),
21+
[] (const pair_type& a,
22+
const pair_type& b) {
23+
return a.second < b.second;
24+
})->second;
25+
}
26+
};

0 commit comments

Comments
 (0)