Advertisement
Oppenheimer

Min # of deletion or insertions to make palindrome

Aug 15th, 2022 (edited)
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. // longest common subsequence
  2. // [1 ,2 ,3, 4]
  3. // subsequnce (order matters but maybe not continuous)
  4. // substring or subarray .. (need to be contigous)
  5. // subset same as subsequence ..
  6. int solve(string s1){
  7.     string s2 = s1;
  8.     reverse(s2.begin(),s2.end());
  9.     int sa = s1.length();
  10.     int sb = sa;
  11.     vector<vector<int>> dp (sa+1 ,vector<int>(sb+1,0));
  12.     // a represents the ath element .. b represents the knapsack present
  13.    
  14.     for(int a=1;a<=sa;a++){
  15.         for(int b=1;b<=sb;b++){
  16.             if(s1[a-1] == s2[b-1]){
  17.             dp[a][b] = 1 + dp[a-1][b-1]; //here we can choose ith element again
  18.             }else{
  19.             dp[a][b] = max(dp[a-1][b] , dp[a][b-1]); // cant choose the ath element becuase its weight is more
  20.             }
  21.         }
  22.     }
  23.     return (sa - dp[sa][sa]);
  24.  
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement