Advertisement
imashutosh51

Longest Common Substring

Jul 23rd, 2022 (edited)
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. //M1
  2. /*
  3. We will take a dp array of n*m where 1 to n(rows) represents the index of string1 and same goes for m(columns)
  4. arr[i][j] represents the length of substring ending at ith index in s1 and jtj index in s2 because it is
  5. substring so at (i,j) we will be having answer for (i-1,j-1)th index.
  6. */
  7. class Solution{
  8.     public:
  9.    
  10.     int longestCommonSubstr (string text1, string text2, int n, int m){
  11.         int n1=text1.size(),n2=text2.size();
  12.         int ma=0;
  13.           int arr[n1+1][n2+1];
  14.             for(int i=0;i<=n1;i++)   //0 size string can form only 0 size common substring with any size substring
  15.                 arr[i][0]=0;
  16.             for(int j=0;j<=n2;j++)   //0 size substring can form only 0 size common substring with any size string
  17.                  arr[0][j]=0;
  18.             for(int i=1;i<=n1;i++){   //if current character matches,then maximum length of substring upto that
  19.                 for(int j=1;j<=n2;j++){// will be the maximum of last visited character ie. arr[i-1][j-1]+1;
  20.                     if(text1[i-1]==text2[j-1])
  21.                          arr[i][j]=arr[i-1][j-1]+1;
  22.                     else arr[i][j]=0;    //if not matches,then substring can't go ahead and current substring broke
  23.                     ma=max(arr[i][j],ma); //so arr[i][j]=0;
  24.                 }
  25.             }
  26.         return ma;  //for finding max_length substring,we wen through whole dp table
  27.     }
  28. };
  29. //M2
  30.  public int lcsSubstrMemo(char[] s1, char[] s2, int m, int n, int c, int[][] t) {
  31.             if(m == 0 || n == 0) {
  32.                 return c;
  33.             }
  34.             if (t[m-1][n-1] != -1) return t[m-1][n-1];
  35.             if(s1[m - 1] == s2[n - 1]) {
  36.                 c = lcsSubstr(s1, s2, m - 1, n - 1, c + 1);
  37.             } else {
  38.                 c2 = Math.max(lcsSubstr(s1, s2, m, n - 1, 0), lcsSubstr(s1, s2, m - 1, n, 0));
  39.             }
  40.             t[m - 1][n - 1] = Math.max(c, c2);
  41.             return t[m-1][n-1];
  42.         }
  43.  
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement