Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //M1
- /*
- 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)
- arr[i][j] represents the length of substring ending at ith index in s1 and jtj index in s2 because it is
- substring so at (i,j) we will be having answer for (i-1,j-1)th index.
- */
- class Solution{
- public:
- int longestCommonSubstr (string text1, string text2, int n, int m){
- int n1=text1.size(),n2=text2.size();
- int ma=0;
- int arr[n1+1][n2+1];
- for(int i=0;i<=n1;i++) //0 size string can form only 0 size common substring with any size substring
- arr[i][0]=0;
- for(int j=0;j<=n2;j++) //0 size substring can form only 0 size common substring with any size string
- arr[0][j]=0;
- for(int i=1;i<=n1;i++){ //if current character matches,then maximum length of substring upto that
- for(int j=1;j<=n2;j++){// will be the maximum of last visited character ie. arr[i-1][j-1]+1;
- if(text1[i-1]==text2[j-1])
- arr[i][j]=arr[i-1][j-1]+1;
- else arr[i][j]=0; //if not matches,then substring can't go ahead and current substring broke
- ma=max(arr[i][j],ma); //so arr[i][j]=0;
- }
- }
- return ma; //for finding max_length substring,we wen through whole dp table
- }
- };
- //M2
- public int lcsSubstrMemo(char[] s1, char[] s2, int m, int n, int c, int[][] t) {
- if(m == 0 || n == 0) {
- return c;
- }
- if (t[m-1][n-1] != -1) return t[m-1][n-1];
- if(s1[m - 1] == s2[n - 1]) {
- c = lcsSubstr(s1, s2, m - 1, n - 1, c + 1);
- } else {
- c2 = Math.max(lcsSubstr(s1, s2, m, n - 1, 0), lcsSubstr(s1, s2, m - 1, n, 0));
- }
- t[m - 1][n - 1] = Math.max(c, c2);
- return t[m-1][n-1];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement