Leetcode 1048. The longest string chain

Leetcode 1048. The longest string chain

topic

给出一个单词列表,其中每个单词都由小写英文字母组成。

如果我们可以在 word1 的任何地方添加一个字母使其变成 word2,那么我们认为 word1 是 word2 的前身。例如,"abc" 是 "abac" 的前身。

词链是单词 [word_1, word_2, ..., word_k] 组成的序列,k >= 1,其中 word_1 是 word_2 的前身,word_2 是 word_3 的前身,依此类推。

从给定单词列表 words 中选择单词组成词链,返回词链的最长可能长度。

Example:

输入:["a","b","ba","bca","bda","bdca"]
输出:4
解释:最长单词链之一为 "a","ba","bda","bdca"。

Ideas

  • In fact, this question is basically the same routine as the longest ascending subsequence. Just pay attention to the following points.
  • The good examples given in the title happen to be sorted, so we need to sort them by size.
  • Pay attention to the sentence
我们可以在 word1 的任何地方添加一个字母使其变成 word2
  • We can only add one letter, that is to say, the length of word1 and word2 is exactly 1, so when judging whether it is a subsequence or not, we need to judge the length

Code

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;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43891775/article/details/112346445
Recommended