Given a list of words, each word consists of English lowercase letters.
Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac".
A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.
Return the longest possible length of a word chain with words chosen from the given list of words.
Example 1:
Input: ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: one of the longest word chain is "a","ba","bda","bdca".
Note:
1 <= words.length <= 10001 <= words[i].length <= 16words[i]only consists of English lowercase letters.
Related Topics:
Hash Table, Dynamic Programming
// OJ: https://leetcode.com/problems/longest-string-chain/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(N)
class Solution {
public:
int longestStrChain(vector<string>& A) {
int N = A.size(), ans = 1;
vector<int> id(N), len(N, 1);
iota(begin(id), end(id), 0);
sort(begin(id), end(id), [&](int a, int b) { return A[a].size() < A[b].size(); });
vector<array<int, 26>> cnts(N);
map<int, vector<int>> m;
for (int i = 0; i < N; ++i) {
for (char c : A[i]) cnts[i][c - 'a']++;
m[A[i].size()].push_back(i);
}
for (auto &[cnt, ids] : m) {
if (m.count(cnt - 1) == 0) continue;
for (int i : ids) {
for (int j : m[cnt - 1]) {
int diff = 0;
for (int k = 0; k < 26; ++k) {
diff += abs(cnts[i][k] - cnts[j][k]);
if (diff > 1) break;
}
if (diff == 1) len[i] = max(len[i], len[j] + 1);
}
ans = max(ans, len[i]);
}
}
return ans;
}
};// OJ: https://leetcode.com/problems/longest-string-chain/
// Author: github.com/lzl124631x
// Time: O(NSS)
// Space: O(NS)
// Ref: https://leetcode.com/problems/longest-string-chain/discuss/294890/C%2B%2BJavaPython-DP-Solution
class Solution {
public:
int longestStrChain(vector<string>& A) {
auto cmp = [](string &a, string &b) { return a.size() < b.size(); };
sort(begin(A), end(A), cmp);
unordered_map<string, int> dp;
int ans = 1;
for (auto &s : A) {
for (int i = 0; i < s.size(); ++i) {
dp[s] = max(dp[s], dp[s.substr(0, i) + s.substr(i + 1)] + 1);
ans = max(ans, dp[s]);
}
}
return ans;
}
};