-
Notifications
You must be signed in to change notification settings - Fork 391
Expand file tree
/
Copy pathLongestCommonSubstring.java
More file actions
79 lines (69 loc) · 2.07 KB
/
LongestCommonSubstring.java
File metadata and controls
79 lines (69 loc) · 2.07 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Problem: Longest Common Substring
*
* Given two strings s1 and s2, find the length of the longest common substring.
* A substring is a contiguous sequence of characters.
*
* Example:
* Input:
* s1 = "abcdxyz"
* s2 = "xyzabcd"
*
* Output:
* 4
*
* Explanation:
* The longest common substrings are "abcd" and "xyz".
*
* ----------------------------------------------------
* Approach: Dynamic Programming
*
* Let dp[i][j] represent the length of the longest common substring
* ending at index (i - 1) in s1 and (j - 1) in s2.
*
* If s1[i - 1] == s2[j - 1]:
* dp[i][j] = dp[i - 1][j - 1] + 1
* Else:
* dp[i][j] = 0
*
* We keep track of the maximum value in the DP table.
*
* ----------------------------------------------------
* Time Complexity: O(n * m)
* Space Complexity: O(n * m)
*/
public class LongestCommonSubstring {
/**
* Returns the length of the longest common substring
* between two given strings.
*/
public static int longestCommonSubstring(String s1, String s2) {
int n = s1.length();
int m = s2.length();
// DP table where dp[i][j] stores length of
// longest common substring ending at s1[i-1] and s2[j-1]
int[][] dp = new int[n + 1][m + 1];
int maxLength = 0;
// Build the DP table
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// If characters match, extend the substring
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
maxLength = Math.max(maxLength, dp[i][j]);
} else {
// Reset to 0 when characters do not match
dp[i][j] = 0;
}
}
}
return maxLength;
}
// Driver code for quick testing
public static void main(String[] args) {
String s1 = "abcdxyz";
String s2 = "xyzabcd";
System.out.println("Length of Longest Common Substring: "
+ longestCommonSubstring(s1, s2));
}
}