Advertisement
nikunjsoni

1048

May 17th, 2021
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int longestStrChain(vector<string>& words) {
  4.         unordered_map<string, int> dp;
  5.         for(auto word: words)
  6.             dp[word] = 1;
  7.        
  8.         sort(words.begin(), words.end(), [](auto &a, auto &b){return a.length()>b.length();});
  9.         int ans = 1;
  10.         for(auto word: words){
  11.             string newWord = "";
  12.             for(int i=0; i<word.size(); i++){
  13.                 newWord = word.substr(0,i);
  14.                 if(i+1 < word.size())
  15.                     newWord += word.substr(i+1);
  16.                 if(dp.count(newWord)){
  17.                     dp[newWord] = max(dp[newWord], dp[word]+1);
  18.                     ans = max(ans, dp[newWord]);
  19.                 }
  20.             }
  21.         }
  22.         return ans;
  23.     }
  24. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement