Longest common subsequence: Difference between revisions

→‎Dynamic programming: Deleting section. Wrong algorithm - this is for a substring, not a subsequence.
(→‎{{header|C sharp|C#}}: To distinguish this code block.)
(→‎Dynamic programming: Deleting section. Wrong algorithm - this is for a substring, not a subsequence.)
Line 558:
}
}
}
}</lang>
 
===Dynamic programming===
Based on algorithm from Wikipedia and the above calling code.
 
<lang csharp>
using System;
 
namespace LCS
{
class Program
{
static void Main(string[] args)
{
string word1 = "thisisatest";
string word2 = "testing123testing";
Console.WriteLine(lcs(word1, word2));
Console.ReadKey();
}
 
public static string lcs(string a, string b)
{
int[,] lengths = new int[a.Length, b.Length];
int greatestLength = 0;
string output = "";
for (i = 0; i < a.Length; i++)
{
for (j = 0; j < b.Length; j++)
{
if (a[i] == b[j])
{
if (i == 0 || j == 0)
{
lengths[i, j] = 1;
}
else
{
lengths[i, j] = lengths[i - 1, j - 1] + 1;
}
if (lengths[i, j] > greatestLength)
{
greatestLength = lengths[i, j];
output = a.Substring(i - greatestLength, greatestLength);
}
}
else
{
lengths[i, j] = 0;
}
}
}
}
return output;
}
}</lang>