A string Z is a merge of two other strings X and Y if Z is a concatenation of substrings of X and Y , in order. For example “strMERingGE” is a merge of “string” and “MERGE”. Give a dynamic programming algorithm that takes 3 strings and tests if the third is a merge of the first two.
This problem looks like a variation of the longest common subsequence problem, I tried this algorithm but I an not sure about it.
public static String concat(String s1, String s2) {
if (string.IsNullOrEmpty(s1))
return s2;
if (string.IsNullOrEmpty(s2) )
return s1;
int len1 = s1.Length - 1;
char last1 = s1[len1];
char first2 = s2[0];
if (s1[len1 - indexOfLast2] == first2)
{
int inLast2 = s2.LastIn(last1, Math.Min(len1, s2.Length - 1));
while (inLast2 != -1)
{
int x = inLast2;
while ((x != -1) && (s1[len1 - inLast2 + x] == s2[x]))
x--;
if (x == -1)
return s1 + s2.Substring(Last2 + 1);
}
inLast2 = s2.LastIn(last1, inLast2 - 1);
}
if ( s1 + s2.Substring(Last2 + 1) == 2)
return inLast2 +1;