-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-LongestStringChain.cpp
More file actions
50 lines (36 loc) · 1.4 KB
/
Copy pathLeetCode-LongestStringChain.cpp
File metadata and controls
50 lines (36 loc) · 1.4 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public:
int longestStrChain(vector<string>& words) {
// let n be the number of words
// let m be the length of the longest word
int n = words.size();
sort(words.begin(), words.end(), [](const string& a, const string& b) {
return a.size() < b.size();
});
// longest chain starting at dp(i)
int dp[1001];
memset(dp, 0, sizeof(dp));
int ans = dp[n - 1] = 1;
// O(n^2*m)
for (int i = n - 2; i >= 0; --i) {
dp[i] = 1;
for (int j = i + 1; j < n; ++j) {
// compare two words
if (words[j].size() == words[i].size()) continue;
if (words[j].size() - words[i].size() > 1) break;
int l = 0;
for (int k = 0, p = 0; k < words[j].size(); ++k) {
if (words[j][k] == words[i][p]) {
++l;
++p;
continue;
}
}
assert(l <= words[j].size() - 1);
if (l == words[j].size() - 1) dp[i] = max(dp[i], dp[j] + 1);
}
ans = max(ans, dp[i]);
}
return ans;
}
};