C# 最长公共子序列
2014-10-15 15:37
344 查看
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;
}
}
下面是输出结果截图:
本程序实现了字符串的最长公共子序列的方法: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;
}
}
下面是输出结果截图:
相关文章推荐
- <<展现C#>>第四章 C#类型(修订)
- 【我们一起写框架】C#的AOP框架
- VB程序员眼中的C# 10(end)
- VB程序员眼中的C# 9
- VB程序员眼中的C# 7
- VB程序员眼中的C# 8
- VB程序员眼中的C# 5
- VB程序员眼中的C# 6
- VB程序员眼中的C# 4
- VB程序员眼中的C# 3
- VB程序员眼中的C# 2
- VB程序员眼中的C#
- C#抢鲜快报之FAQ20
- <展现 C#> 第一章 C#简介(修订)
- <<展现C#>> 第二章 NGWS Runtime 技术基础(修订)
- <<展现C#>> 前言(补充) 和第三章 第一个C#程序(修订)
- ping程序的C#实现
- <<展现C#>> 第五章 类(修订)
- <<展现C#>>第六章 控制语句(修订)
- <<展现C#>> 第七章 异常处理(修订)