-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonSubstring.java
More file actions
29 lines (23 loc) · 1006 Bytes
/
Copy pathLongestCommonSubstring.java
File metadata and controls
29 lines (23 loc) · 1006 Bytes
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
package codes;
public class LongestCommonSubstring {
static String longestCommonSubstring(String s1, String s2) {
int[][] lengthMat = new int[s1.length()+1][s2.length()+1];
int maxLength = 0, maxLengthIdx = 0;
for(int i = 1; i <= s1.length(); i++) {
for(int j = 1; j <= s2.length(); j++) {
if(s1.charAt(i-1) == s2.charAt(j-1)) {
lengthMat[i][j] = lengthMat[i-1][j-1] + 1;
if(maxLength < lengthMat[i][j]) {
maxLength = lengthMat[i][j];
maxLengthIdx = i;
System.out.println(maxLength + " " + maxLengthIdx);
}
}
}
}
return s1.substring(maxLengthIdx - maxLength, maxLengthIdx);
}
public static void main(String[] args) {
System.out.println(longestCommonSubstring("hihellohi", "hihedehellode"));
}
}