problem:https://leetcode.com/problems/longest-string-chain/
爬台阶类型问题。从长度为k转换为长度为k + 1的字符串。此处通过删掉一个字符,查看删掉后的字符串是否存在来判断能否转换。
bool cmp(const string &s1, const string &s2) { return s1.size() == s2.size() ? s1 < s2 : s1.size() < s2.size(); } class Solution { public: int longestStrChain(vector<string>& words) { vector<int> dp(words.size(), 1); map<string, int, function<bool(const string &, const string &)>> mapWord(cmp); for (int i = 0;i<words.size();i++) { mapWord[words[i]] = i; } int result = 1; int i = 0; for (auto it = mapWord.begin();it != mapWord.end();it++) { string word = it->first; it->second = i; //cout << word << endl; for (int j = 0;j<word.size();j++) { string subWord = word.substr(0, j) + word.substr(j + 1, word.size() - j); if (mapWord.find(subWord) != mapWord.end()) { int idx = mapWord[subWord]; dp[i] = max(dp[i], dp[idx] + 1); } } if (dp[i] > result) result = dp[i]; i++; } return result; } };