Advertisement
Oppenheimer

sequence pattern matching

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