forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonSubstring.java
More file actions
55 lines (49 loc) · 1.66 KB
/
Copy pathLongestCommonSubstring.java
File metadata and controls
55 lines (49 loc) · 1.66 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
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.thealgorithms.strings;
/**
* Longest Common Substring finds the longest string that is a
* contiguous substring of two input strings.
* Example: "abcdef" and "zcdemf" -> "cde"
*
* @see <a href="https://en.wikipedia.org/wiki/Longest_common_substring">
* Wikipedia: Longest Common Substring</a>
*
* author: Vraj Prajapati @Rosander0
*/
public final class LongestCommonSubstring {
private LongestCommonSubstring() {
// Utility class
}
/**
* Finds the longest common substring of two strings.
*
* @param a First input string
* @param b Second input string
* @return The longest common substring, or empty string if none exists.
* If multiple substrings share the maximum length, the first one found is returned.
*/
public static String longestCommonSubstring(final String a, final String b) {
if (a == null || b == null || a.isEmpty() || b.isEmpty()) {
return "";
}
int[][] dp = new int[a.length() + 1][b.length() + 1];
int maxLength = 0;
int endIndex = 0;
for (int i = 1; i <= a.length(); i++) {
for (int j = 1; j <= b.length(); j++) {
if (a.charAt(i - 1) == b.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;
}
}
}
if (maxLength == 0) {
return "";
}
return a.substring(endIndex - maxLength, endIndex);
}
}