-
Notifications
You must be signed in to change notification settings - Fork 405
Expand file tree
/
Copy pathLongest-Common-Substring.java
More file actions
42 lines (35 loc) · 1.48 KB
/
Longest-Common-Substring.java
File metadata and controls
42 lines (35 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class LongestCommonSubstring {
public static String findLongestCommonSubstring(String str1, String str2) {
int m = str1.length();
int n = str2.length();
// Create a 2D table to store the lengths of common substrings
int[][] dp = new int[m + 1][n + 1];
// To store the length of the longest common substring found so far
int maxLength = 0;
// To store the ending position of the longest common substring found so far
int endIndex = 0;
// Fill the dp table
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
if (dp[i][j] > maxLength) {
maxLength = dp[i][j];
endIndex = i;
}
} else {
dp[i][j] = 0;
}
}
}
// Extract the longest common substring using endIndex and maxLength
String longestCommonSubstring = str1.substring(endIndex - maxLength, endIndex);
return longestCommonSubstring;
}
public static void main(String[] args) {
String str1 = "ABABC";
String str2 = "BABC";
String lcs = findLongestCommonSubstring(str1, str2);
System.out.println("Longest Common Substring: " + lcs); // Output: "BABC"
}
}