jayati

Longest Common Subsequence

Oct 27th, 2023
1,133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. const int mod=1e9+7;
  4. using namespace std;
  5.  
  6. // } Driver Code Ends
  7. // function to find longest common subsequence
  8.  
  9. class Solution
  10. {
  11.     public:
  12.     //Function to find the length of longest common subsequence in two strings.
  13.     int lcs(int n, int m, string s1, string s2)
  14.     {
  15.         // your code here
  16.          // your code here
  17.         vector<vector<int>> dp(n+1,vector<int> (m+1,0));
  18.         for(int j=0;j<=m;j++)
  19.         {
  20.             dp[0][j]=0;
  21.         }
  22.          for(int j=0;j<=n;j++)
  23.         {
  24.             dp[j][0]=0;
  25.         }
  26.         int ans=0;
  27.         for(int i=1;i<=n;i++)
  28.         {
  29.             for(int j=1;j<=m;j++)
  30.             {
  31.                 if(s1[i-1]==s2[j-1])
  32.                 {
  33.                     dp[i][j] = 1 + dp[i-1][j-1];
  34.                     ans = max(ans,dp[i][j]);
  35.                 }
  36.                 else
  37.                 {
  38.                     dp[i][j]=max(dp[i][j-1],dp[i-1][j]);
  39.                 }
  40.                
  41.             }
  42.         }
  43.         return ans;
  44.     }
  45. };
  46.  
  47.  
  48. //{ Driver Code Starts.
  49. int main()
  50. {
  51.     int t,n,m;
  52.     cin>>t;
  53.     while(t--)
  54.     {
  55.         cin>>n>>m;          // Take size of both the strings as input
  56.         string s1,s2;
  57.         cin>>s1>>s2;        // Take both the string as input
  58.         Solution ob;
  59.         cout << ob.lcs(n, m, s1, s2) << endl;
  60.     }
  61.     return 0;
  62. }
  63.  
  64. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment