- 1048. Longest String Chain
- 1048. Longest String Chain
- LeetCode #1048 Longest String Ch
- Leetcode 1048. Longest String Ch
- LeetCode 1048. Longest String Ch
- 524. Longest Word in Dictionary
- 524. Longest Word in Dictionary
- LeetCode 5: Longest Palindromic
- Longest Substring Without Repeat
- 3. Longest Substring Without Rep
思路:
动态规划
用一个字典,map
记录每个单词最长的chain值
将所有单词按长度从小到大排序,对每个单词,查询缺少一个字母的单词的最长的chain值。
class Solution {
public:
int longestStrChain(vector<string>& words) {
sort(words.begin(), words.end(), [](string& s1, string& s2){
return s1.length() < s2.length();
});
unordered_map<string, int> dp;
int res = -1;
for(auto& word : words){
for(int i = 0; i < word.length(); i++){
dp[word] = max(dp[word], dp[word.substr(0, i)+word.substr(i+1)] + 1);
}
res = max(res, dp[word]);
}
return res;
}
};
网友评论