java string to find two longest common substring

Reference: https: //segmentfault.com/a/1190000007963594 

They are optimized spatial complexity

public static String LCS(String str1, String str2) {
int max = 0; // record the length of the longest string
int index = 0; // record the last subscript longest string of the same
if (str1.length() > str2.length()) { 
String s = str1;
str1 = str2;
str2 = s;

int [] arr = new int [str1.length ()]; // this defines only one-dimensional array, it is defined herein two-dimensional array
int uLeft = 0; // upper left recording digital
for (int i = 0; i < str2.length(); i++) 
for (int j = 0; j < str1.length(); j++){
if (str1.charAt(j) == str2.charAt(i)) {
if (j == 0)
arr[0] = 1;
else {
int a = arr[j];
arr[j] = uLeft + 1;
uLeft = a;
}
if (arr[j] > max) {
max = arr[j];
index = j + 1;
if (max == str1.length ()) // show substring str1 str2 directly returns str1
return str1;
}
} else {
uLeft = arr[j];
arr[j] = 0;
}
}
return str1.substring(index - max, index);
}

Published 16 original articles · won praise 3 · Views 4538

Guess you like

Origin blog.csdn.net/qq_29697901/article/details/78282149