Article Directory
1. Title
Given a list of words, each word consists of lowercase English letters.
If we can add a letter anywhere in word1 to make it word2, then we think word1 is the predecessor of word2. For example, "abc" is the predecessor of "abac".
A word chain is a sequence of words [word_1, word_2, …, word_k], k >= 1, where word_1 is the predecessor of word_2, word_2 is the predecessor of word_3, and so on.
Select words from the given word list words to form a word chain, and return the longest possible length of the word chain .
示例:
输入:["a","b","ba","bca","bda","bdca"]
输出:4
解释:最长单词链之一为 "a","ba","bda","bdca"。
提示:
1 <= words.length <= 1000
1 <= words[i].length <= 16
words[i] 仅由小写英文字母组成。
Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/longest-string-chain
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
2. Problem solving
- Sort by length first
- Establish a hash map of a string and its serial number
dp[i]
Expressed in wordsi
ending chain of maximum length
see code comments
class Solution {
public:
int longestStrChain(vector<string>& words) {
sort(words.begin(),words.end(),[&](auto a, auto b){
return a.size() < b.size();//按长度排序
});
int n = words.size(), maxlen = 1, i, j, k;
unordered_map<string, int> s;//哈希
string tmp;
vector<int> dp(n, 1);
for(i = 0; i < n-1; ++i)
{
s[words[i]] = i;//建立哈希
j = i+1;
for(k = 0; k < words[j].size(); ++k)
{
//遍历后面长的单词,枚举所有少一个字符的子串
tmp = words[j].substr(0,k)+words[j].substr(k+1);
if(s.find(tmp) != s.end())//存在这个子串
{
dp[j] = max(dp[j], dp[s[tmp]]+1);
maxlen = max(maxlen, dp[j]);
}
}
}
return maxlen;
}
};
268 ms 25.2 MB
My CSDN blog address https://michael.blog.csdn.net/
Long press or scan the QR code to follow my official account (Michael Amin), come on together, learn and make progress together!