forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1048.cpp
More file actions
27 lines (19 loc) · 675 Bytes
/
1048.cpp
File metadata and controls
27 lines (19 loc) · 675 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
static bool compare(const string &s1, const string &s2) {
return s1.length() < s2.length();
}
public:
int longestStrChain(vector<string>& words) {
sort(words.begin(), words.end(), compare);
unordered_map<string, int> dp;
int res = 0;
for (string& w : words) {
for (int i = 0; i < w.length(); i++) {
string pre = w.substr(0, i) + w.substr(i + 1);
dp[w] = max(dp[w], dp.find(pre) == dp.end() ? 1 : dp[pre] + 1);
}
res = max(res, dp[w]);
}
return res;
}
};