From 2aaf4140edfaad80d55f5a151af06ad04818ad9b Mon Sep 17 00:00:00 2001 From: mohd sahil farooq kacchi Date: Fri, 1 Oct 2021 18:57:13 +0530 Subject: [PATCH] added the solution for longest common substring in java --- Java/LongestCommonSubstring.java | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Java/LongestCommonSubstring.java diff --git a/Java/LongestCommonSubstring.java b/Java/LongestCommonSubstring.java new file mode 100644 index 00000000..f0dd8398 --- /dev/null +++ b/Java/LongestCommonSubstring.java @@ -0,0 +1,49 @@ +// Calculate the lenght of longest Common substring +//Solution: +public class LongestCommonSubstring{ + + public static void main(String []args){ + String a = "abcdxyz"; + String b = "xyzabcd"; + int i,j; + int lena = a.length(); + int lenb = b.length(); + int[][] arr = new int[lena+ 1][lenb+1]; + + for(i = 0; i<= lena; i++ ) + { + for(j = 0;j<=lenb; j++) + { + if(i==0 || j==0) + arr[i][j] = 0; + } + } + for(i = 1; i<= lena; i++ ) + { + for(j = 1;j<=lenb; j++) + { + if(a.charAt(i-1) == b.charAt(j-1)) + { + arr[i][j] = 1 + arr[i-1][j-1]; + } + else + arr[i][j] = 0; + } + } + int max =0; + for(i = 0; i<= lena; i++ ) + { + for(j = 0;j<=lenb; j++) + { + + if(arr[i][j]>max) + { + max = arr[i][j]; + } + } + } + + + System.out.println("Longest Common Substring : "+max+" length"); + } +} \ No newline at end of file