Skip to content

Commit 7bb9b67

Browse files
authored
Create Find_Longest_Common_Substring.java
1 parent a025038 commit 7bb9b67

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
3+
Using the DP Approach-
4+
We construct a matrix to keep track of maximal length suffix of all substrings. We can find the maximal value from this matrix and traverse from that cell diognally upwards till the cell value becomes 0.
5+
6+
*/
7+
8+
public void printLCStr(String A, String B, int n, int m){
9+
int lcs[][] = new int[n+1][m+1];
10+
11+
//to store length of longest substring
12+
int maxLen = 0;
13+
14+
//to store row and column values which point to the end of the longest substring
15+
int row = 0;
16+
int col = 0;
17+
18+
for(int i=0 ; i<=n ; i++){
19+
for(int j=0 ; j<=m ; j++){
20+
if(i==0 || j==0) lcs[i][j] = 0;
21+
else if(A.charAt(i-1) == B.charAt(j-1)){
22+
lcs[i][j] = lcs[i-1][j-1] + 1;
23+
24+
if(maxLen < lcs[i][j]){
25+
maxLen = lcs[i][j];
26+
row = i;
27+
col = j;
28+
}
29+
}
30+
else lcs[i][j] = 0;
31+
}
32+
}
33+
34+
if(maxLen == 0){
35+
System.out.println("No Substring");
36+
}
37+
38+
String resStr = "";
39+
while(lcs[row][col]!=0){
40+
resStr = A.charAt(row-1)+resStr;
41+
row--;
42+
col--;
43+
}
44+
45+
System.out.println(resStr);
46+
}

0 commit comments

Comments
 (0)