题目描述

分析

使用map保存已经检查过的字符串以及链长度。
每一次检查除去中间某一个字符后拼接而成的字符串在之前的长度。
例如:

  1. abcdef ->bcdef,acdef,abdef,abcef,abcdf,abcde

依次检查这几个是否存在,

  • 如果存在,m[abcdef]=max(m[bcdef]+1,...);;
  • 如果不存在,m[abcdef]=max(1,m[abcdef]);

记忆化搜索。

答案

  1. class Solution {
  2. public:
  3. static bool cmp(const string &lhs, const string &rhs) {
  4. return lhs.size() < rhs.size();
  5. }
  6. int longestStrChain(vector<string>& words) {
  7. sort(words.begin(), words.end(), cmp);
  8. map<string, int> m;
  9. int m_a = 0;
  10. for(int i = 0; i < words.size(); i++) {
  11. m[words[i]] = 0;
  12. for (int j = 0; j < words[i].size(); j++) {
  13. string temp = words[i].substr(0, j) + words[i].substr(j + 1, words[i].size() - j - 1);
  14. if (m.count(temp) == 0)
  15. m[words[i]] = max(1, m[words[i]]);
  16. else
  17. m[words[i]] = max(m[temp] + 1, m[words[i]]);
  18. m_a = max(m[words[i]], m_a);
  19. }
  20. }
  21. return m_a;
  22. }
  23. };