鱼C论坛

 找回密码
 立即注册
查看: 1755|回复: 0

[学习笔记] leetcode 1048. Longest String Chain

[复制链接]
发表于 2019-10-18 13:24:37 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Given a list of words, each word consists of English lowercase letters.

  2. Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2.  For example, "abc" is a predecessor of "abac".

  3. A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.

  4. Return the longest possible length of a word chain with words chosen from the given list of words.



  5. Example 1:

  6. Input: ["a","b","ba","bca","bda","bdca"]
  7. Output: 4
  8. Explanation: one of the longest word chain is "a","ba","bda","bdca".


  9. Note:

  10. 1 <= words.length <= 1000
  11. 1 <= words[i].length <= 16
  12. words[i] only consists of English lowercase letters.
复制代码

  1. class Solution {
  2. public:
  3.     int longestStrChain(vector<string>& words) {
  4.         if(words.size() == 0) return 0;
  5.         sort(words.begin(),words.end(),cmp);
  6.         vector <int> dp(words.size(),0);
  7.         dp[0] = 1;
  8.         int Max = 1;
  9.         for(int i = 1; i< words.size();i++){
  10.             int local = 0;
  11.             for(int j = 0 ; j < i ; j++){
  12.                 if(words[i].size() - words[j].size() == 1 && isPredecessor(words[j], words[i])){   
  13.                     local = max(local, dp[j]);
  14.                 }
  15.                
  16.             }
  17.             dp[i] = local +1;
  18.             
  19.             Max = max(Max, dp[i]);
  20.         }
  21.         
  22.         
  23.         return Max;
  24.     }

  25. private:
  26.     static bool cmp (const string &a, const string &b){
  27.         return a.size() < b.size();
  28.     }
  29.    
  30.     int isPredecessor(string a, string b){
  31.         sort(a.begin(),a.end());
  32.         sort(b.begin(),b.end());
  33.         int count = 0;
  34.         int i = 0, j = 0;
  35.         while(i != a.size() && j != b.size()){
  36.             if(a[i] != b[j]){
  37.                 j++;
  38.                 count++;
  39.             }
  40.             else{
  41.                 i++;
  42.                 j++;
  43.             }
  44.         }
  45.         if(count == 0 && i == a.size() && j != b.size()) return 1;
  46.         if(count == 1) return 1;
  47.         else return 0;
  48.         
  49.     }
  50.    
  51.    
  52. };
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-18 15:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表