Advertisement
Singasking

Untitled

Jul 21st, 2023
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class Solution {
  4.  
  5. int isPred(string &pred,string &suc) {
  6. if((pred.length()+1)!=suc.length()) return 0; //False
  7.  
  8. int misCount=0;
  9. int i=0;
  10. int j=0;
  11. int l1 = pred.length();
  12. int l2 = suc.length();
  13. while((i<l1)&&(j<l2)) {
  14. if(pred[i]!=suc[j]) {
  15. misCount+=1;
  16. j+=1;
  17. }
  18. if(misCount>1) return 0;
  19. i+=1;
  20. j+=1;
  21.  
  22. }
  23. return 1;
  24. }
  25.  
  26. public:
  27. static bool comparex(string &a,string &b) {
  28. return (a.length()<b.length());
  29. }
  30.  
  31. int longestStrChain(vector<string>& words) {
  32. int n = words.size();
  33.  
  34. sort(words.begin(),words.end(),comparex);
  35.  
  36. vector<int> dp(n+2,1);
  37. int maxCount=1;
  38. for(int i=0;i<n;i++) {
  39. for(int pred=0;pred<i;pred++) {
  40. if((dp[pred]+1>dp[i]) && isPred(words[pred],words[i])) {
  41. dp[i] = dp[pred]+1;
  42. maxCount = max(maxCount,dp[i]);
  43. }
  44. }
  45. }
  46.  
  47. return maxCount;
  48. }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement