Leetcode1048。最長の文字列チェーン

Leetcode1048。最長の文字列チェーン

トピック

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

如果我们可以在 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"。

アイデア

  • 実際、この質問は基本的に最長昇順部分列と同じルーチンです。次の点に注意してください。
  • タイトルにある良い例はたまたまソートされているので、サイズでソートする必要があります。
  • 文に注意してください
我们可以在 word1 的任何地方添加一个字母使其变成 word2
  • 追加できる文字は1文字だけです。つまり、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;
    }
};

おすすめ

転載: blog.csdn.net/weixin_43891775/article/details/112346445