题目描述
分析
使用map保存已经检查过的字符串以及链长度。
每一次检查除去中间某一个字符后拼接而成的字符串在之前的长度。
例如:
abcdef ->bcdef,acdef,abdef,abcef,abcdf,abcde
依次检查这几个是否存在,
- 如果存在,
m[abcdef]=max(m[bcdef]+1,...);; - 如果不存在,
m[abcdef]=max(1,m[abcdef]);
答案
class Solution {public:static bool cmp(const string &lhs, const string &rhs) {return lhs.size() < rhs.size();}int longestStrChain(vector<string>& words) {sort(words.begin(), words.end(), cmp);map<string, int> m;int m_a = 0;for(int i = 0; i < words.size(); i++) {m[words[i]] = 0;for (int j = 0; j < words[i].size(); j++) {string temp = words[i].substr(0, j) + words[i].substr(j + 1, words[i].size() - j - 1);if (m.count(temp) == 0)m[words[i]] = max(1, m[words[i]]);elsem[words[i]] = max(m[temp] + 1, m[words[i]]);m_a = max(m[words[i]], m_a);}}return m_a;}};
