Leetcode 1048. 最长字符串链
题目
给出一个单词列表,其中每个单词都由小写英文字母组成。
如果我们可以在 word1 的任何地方添加一个字母使其变成 word2,那么我们认为 word1 是 word2 的前身。例如,"abc" 是 "abac" 的前身。
词链是单词 [word_1, word_2, ..., word_k] 组成的序列,k >= 1,其中 word_1 是 word_2 的前身,word_2 是 word_3 的前身,依此类推。
从给定单词列表 words 中选择单词组成词链,返回词链的最长可能长度。
示例:
输入:["a","b","ba","bca","bda","bdca"]
输出:4
解释:最长单词链之一为 "a","ba","bda","bdca"。
思路
- 其实这道题目和最长上升子序列基本上是一模一样的套路, 只需要注意如下几个点即可
- 题目中给好的例子刚好是排好序的, 所以我们自己需要按size大小排个序
- 注意题干的这句话
我们可以在 word1 的任何地方添加一个字母使其变成 word2
- 我们只可以添加一个字母, 也就是说word1和word2长度刚好差1, 所以在判断是不是子序列的时候还需要判断长度
代码
class Solution {
public:
bool is_preword(string& a, string& b) {
int idx = 0;
for (auto& ch:a) {
if (ch == b[idx]) {
++idx;
if (idx == b.size()) break;
}
}
return a.size() == b.size() +1 && idx == b.size();
}
int longestStrChain(vector<string>& words) {
int size = words.size(), res = 1;
sort(words.begin(), words.end(), [&](const string& a, const string& b) {
return a.size() < b.size();
});
vector<int> dp(size, 1);
for (int i = 1;i < size;++i) {
for (int j = 0;j < i;++j) {
if (is_preword(words[i], words[j])) {
dp[i] = max(dp[j] + 1, dp[i]);
}
}
res = max(res, dp[i]);
}
return res;
}
};