jayati

Longest Common Substring

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