We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 5291eac commit 7e25337Copy full SHA for 7e25337
C++/longest-string-chain.cpp
@@ -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