Skip to content

Commit a79eacf

Browse files
Create LongestCommonSubstring.java
1 parent 3573900 commit a79eacf

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Calculate the lenght of longest Common substring
2+
//Solution:
3+
4+
public class LongestCommonSubstring{
5+
6+
public static void main(String []args){
7+
String a = "abcde";
8+
String b = "abfce";
9+
int i,j;
10+
int lena = a.length();
11+
int lenb = b.length();
12+
int[][] arr = new int[lena+ 1][lenb+1];
13+
14+
for(i = 0; i<= lena; i++ )
15+
{
16+
for(j = 0;j<=lenb; j++)
17+
{
18+
if(i==0 || j==0)
19+
arr[i][j] = 0;
20+
}
21+
}
22+
for(i = 1; i<= lena; i++ )
23+
{
24+
for(j = 1;j<=lenb; j++)
25+
{
26+
if(a.charAt(i-1) == b.charAt(j-1))
27+
{
28+
arr[i][j] = 1 + arr[i-1][j-1];
29+
}
30+
else
31+
arr[i][j] = 0;
32+
}
33+
}
34+
int max =0;
35+
for(i = 0; i<= lena; i++ )
36+
{
37+
for(j = 0;j<=lenb; j++)
38+
{
39+
if(i==j)
40+
{
41+
if(arr[i][j]>max)
42+
{
43+
max = arr[i][j];
44+
}
45+
}
46+
}
47+
}
48+
49+
System.out.println("Longest Common Substring : "+max+" length");
50+
}
51+
}

0 commit comments

Comments
 (0)