ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[Google] LeetCode 1048 Longest String Chain

2022-08-21 03:30:23  阅读:189  来源: 互联网

标签:predecessor Google word String Chain words word2 chain dp


You are given an array of words where each word consists of lowercase English letters.

\(word_A\) is a predecessor of \(word_B\) if and only if we can insert exactly one letter anywhere in \(word_A\) without changing the order of the other characters to make it equal to \(word_A\).

For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".
A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.

Return the length of the longest possible word chain with words chosen from the given list of words.

Solution

我们用 \(map\) 来定义 \(dp\) 数组。现将原来的序列排序,得到长度从小到大的序列。

定义 \(dp[s]\) 表示以 \(s\) 结尾的最长 word chain 长度,考虑如何转移:

\[dp[s] = \max(dp[s], 1+dp[s']) \]

其中 \(s'\) 为 \(s\) 的前驱。这里用 \(erase\) 函数,我们遍历当前的串 \(s\), 看删去一个位置后得到的 \(s'\) 是否在 \(map\) 中

点击查看代码
class Solution {
private:
    map<string, int> dp;
    int ans = INT_MIN;
public:
    int longestStrChain(vector<string>& words) {
        int n = words.size();
        sort(words.begin(), words.end(),
            [](string& s1, string& s2){return s1.size()<s2.size();});
        for(int i=0;i<n;i++){
            dp[words[i]]=1;
            for(int j=0;j<words[i].size();j++){
                string tmp = words[i];
                tmp.erase(tmp.begin()+j);
                if(dp[tmp])dp[words[i]] = max(1+dp[tmp], dp[words[i]]);
            }
            ans = max(ans, dp[words[i]]);
        }
        return ans;
    }
};

标签:predecessor,Google,word,String,Chain,words,word2,chain,dp
来源: https://www.cnblogs.com/xinyu04/p/16609257.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有