Problem: Given two strings ‘X’ and ‘Y’, find the length of the longest common substring.
My solution keeps running and doesn't reach the base condition. I don't understand why that is?
I have looked at the DP solution but cannot find a satisfactory recursive solution for this problem on the internet.
int lcs_calc(string str1, string str2, int i_1, int i_2, int lcs, int c_lcs)
{
if (i_1 >= str1.length() || i_2 >= str2.length())
{
//end. base cond
return lcs;
}
if (str1[i_1] == str2[i_2])
{
c_lcs++;
if (c_lcs > lcs) lcs = c_lcs;
return lcs_calc(str1, str2, ++i_1, ++i_2, lcs, c_lcs);
}
else
{
if (c_lcs == 0)
{
return max(lcs_calc(str1, str2, ++i_1, i_2, lcs, c_lcs), lcs_calc(str1, str2, i_1, ++i_2, lcs, c_lcs));
}
else
{
c_lcs = 0;
return max(lcs_calc(str1, str2, --i_1, i_2, lcs, c_lcs), lcs_calc(str1, str2, i_1, --i_2, lcs, c_lcs));
}
}
}
Initial Parameters:
str1 = "AABC"
str2 = "ABCD"
i_1 = 0 (index for 1st string)
i_2 = 0 (index for 2nd string)
c_lcs = 0 (length of current common substring)
lcs = 0 (length of longest common substring)
longest common substringorlongest common subsequence, the above attempt seems to point to the latter. - Samer Tufail