Advertisement
Oppenheimer

Min no of insertions anddeletions

Aug 15th, 2022
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 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 , string s2){
  7.     int sa = s1.length();
  8.     int sb = s2.length();
  9.     vector<vector<int>> dp (sa+1 ,vector<int>(sb+1,0));
  10.     // a represents the ath element .. b represents the knapsack present
  11.    
  12.     for(int a=1;a<=sa;a++){
  13.         for(int b=1;b<=sb;b++){
  14.             if(s1[a-1] == s2[b-1]){
  15.             dp[a][b] = 1 + dp[a-1][b-1]; //here we can choose ith element again
  16.             }else{
  17.             dp[a][b] = max(dp[a-1][b] , dp[a][b-1]); // cant choose the ath element becuase its weight is more
  18.             }
  19.         }
  20.     }
  21.    
  22.    int lcs = dp[sa][sb];
  23.     int insertions = sb -lcs;
  24.     int deletions = sa-lcs;
  25.     return insertions + deletions;
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement