¡Hello!
I'm trying to find the longest common substring between two strings with a good time and space complexity, following using dynamic programming. I could find a solution with O(n^2) time and space complexity:
public static String LCS(String s1, String s2){
int maxlen = 0; // stores the max length of LCS
int m = s1.length();
int n = s2.length();
int endingIndex = m; // stores the ending index of LCS in X
// lookup[i][j] stores the length of LCS of substring
// X[0..i-1], Y[0..j-1]
int[][] lookup = new int[m + 1][n + 1];
// fill the lookup table in bottom-up manner
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
// if current character of X and Y matches
if (s1.charAt(i - 1) == s2.charAt(j - 1))
{
lookup[i][j] = lookup[i - 1][j - 1] + 1;
// update the maximum length and ending index
if (lookup[i][j] > maxlen)
{
maxlen = lookup[i][j];
endingIndex = i;
}
}
}
}
// return Longest common substring having length maxlen
return s1.substring(endingIndex - maxlen, endingIndex);
}
My question is: How can I get better space complexity?
Thanks in advance!