-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC1048.cpp
More file actions
executable file
·34 lines (30 loc) · 827 Bytes
/
LC1048.cpp
File metadata and controls
executable file
·34 lines (30 loc) · 827 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
28
29
30
31
32
33
34
/*
Problem Statement: https://leetcode.com/problems/longest-string-chain/
Time: O(n • log n + n • max_len)
Space: O(n • max_len)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
int longestStrChain(vector<string> words) {
int max_len = 0, n = words.size();
unordered_map<string, int> dp;
// sort by lengths
sort(words.begin(), words.end(), [](string& l, string& r) {
return l.length() < r.length();
});
// dynamic programming
for (int i = 0; i < n; i++) {
int len = 1;
for (int j = 0; j < words[i].length(); j++) {
string sub = words[i].substr(0, j) + words[i].substr(j + 1);
auto it = dp.find(sub);
if (it != dp.end())
len = max(1 + it->second, len);
}
dp[words[i]] = len;
max_len = max(len, max_len);
}
return max_len;
}
};