C# 最长公共子序列
本程序实现了字符串的最长公共子序列的方法:str[i,j]数组中保存str1,str2长度分别为0-i,0-j之间的最长公共子序列,s[i,j]数组中保存str1,str2长度分别为0-i,0-j之间的最长公共子序列的长度;
s[i,j]=0,i=0或者j=0
s[i,j]=s[i - 1, j - 1] + 1;str1[i]=str2[j]
s[i,j]=max{s[i - 1, j ],s[i , j-1 ] };str1[i]!=str2[j]
代码如下:
class Program
{
static void Main(string[] args)
{
String[,] str = LCS("bdcaba", "abcbdab");
for (int i = 0; i < str.GetLength(0); i++)
{
for (int j = 0; j < str.GetLength(1); j++)
{
Console.WriteLine(i+" "+j+" "+str[i,j]);
}
}
Console.Read();
}
static String[,] LCS(String str1,String str2)
{
int[,] s = new int[str1.Length+1, str2.Length+1];
String[,] str = new String[str1.Length + 1, str2.Length + 1];
for (int i = 0; i <= str1.Length; i++)
{
for (int j =0; j <= str2.Length; j++)
{
if (i == 0 || j == 0)
{
s[i, j] = 0;
str[i, j] = "";
}
else
{
if (str1.Substring(i - 1, 1) == str2.Substring(j - 1, 1))
{
s[i, j] = s[i - 1, j - 1] + 1;
str[i, j] = str[i - 1, j - 1] + str1.Substring(i - 1, 1);
}
else
{
s[i, j] = s[i - 1, j] > s[i, j - 1] ? s[i - 1, j] : s[i, j - 1];
str[i, j] = s[i - 1, j] > s[i, j - 1] ? str[i - 1, j] : str[i, j - 1];
}
}
}
}
return str;
}
}
{
static void Main(string[] args)
{
String[,] str = LCS("bdcaba", "abcbdab");
for (int i = 0; i < str.GetLength(0); i++)
{
for (int j = 0; j < str.GetLength(1); j++)
{
Console.WriteLine(i+" "+j+" "+str[i,j]);
}
}
Console.Read();
}
static String[,] LCS(String str1,String str2)
{
int[,] s = new int[str1.Length+1, str2.Length+1];
String[,] str = new String[str1.Length + 1, str2.Length + 1];
for (int i = 0; i <= str1.Length; i++)
{
for (int j =0; j <= str2.Length; j++)
{
if (i == 0 || j == 0)
{
s[i, j] = 0;
str[i, j] = "";
}
else
{
if (str1.Substring(i - 1, 1) == str2.Substring(j - 1, 1))
{
s[i, j] = s[i - 1, j - 1] + 1;
str[i, j] = str[i - 1, j - 1] + str1.Substring(i - 1, 1);
}
else
{
s[i, j] = s[i - 1, j] > s[i, j - 1] ? s[i - 1, j] : s[i, j - 1];
str[i, j] = s[i - 1, j] > s[i, j - 1] ? str[i - 1, j] : str[i, j - 1];
}
}
}
}
return str;
}
}
下面是输出结果截图: