比如:
字符串a:asd34ghf7asdJHYio-)00><kds
字符串b:bsd25ghf9sasshio98s<kds
要求得到结果:sd ghf as io <kds
注意:是按顺序得到相同字符串,比如:as 在字符串a中有2处,但是,只能取的第二处的
又如:
字符串a:asd34ghf7assdJHYio-)00><kds(第二个as后多加了一s)
字符串b:bsd25ghf9sasshio98s<kds
按照我的要求,结果是:
sd ghf ass io <kds
再例:
a:abcdcba
b:abcdxxdcba
结果是: abcd cba
经过3天的研究,解决 C#代码如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static int[,] c = new int[8000, 8000];
static string[,] parent = new string[8000, 8000];
public void LCS_Length(string x, string y)
{
int i = 0;
int j = 0;
int m = x.Length;
int n = y.Length;
for (i = 0; i <= m; i++)
c[i, 0] = 0;
for (j = 0; j <= n; j++)
c[0, j] = 0;
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
{
if (x[i-1] == y[j-1])
{
c[i, j] = c[i-1, j-1]+1;
parent[i, j] = "X";
}
else if (c[i-1, j] >= c[i, j-1])
{
c[i, j] = c[i-1, j];
parent[i, j] = "U";
}
else
{
c[i, j] = c[i, j-1];
parent[i, j] = "L";
}
}
}
public void Print_LCS(string[,] parent, string x, int i, int j)
{
if (i == 0 || j == 0)
{
Console.WriteLine();
return;
}
if (parent[i, j] == "X")
{
Print_LCS(parent, x, i - 1, j - 1);
Console.Write(x[i-1]);
//Console.Write(i.ToString(), j.ToString());
}
else if (parent[i, j] == "U")
{
Print_LCS(parent, x, i - 1, j);
Console.Write(" ");
}
else
{
Print_LCS(parent, x, i , j - 1);
//Console.Write(" ");
}
}
public void Print_c(int m, int n)
{
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
Console.Write(c[i, j]);
}
Console.Write("/n");
}
}
public void Print_parent(string x, string y)
{
int m = x.Length;
int n = y.Length;
for (int j = 0; j < n; j++)
{
Console.Write(y[j]+"/t");
}
Console.Write("/n");
for (int i = 1; i <= m; i++)
{
Console.Write(x[i-1]);
for (int j = 1; j <= n; j++)
{
Console.Write(parent[i, j]+"/t");
}
Console.Write("/n");
}
}
static void Main(string[] args)
{
Console.WriteLine("begin...");
//string a = "我爱昵a好孩子";
//string b = "我爱ab吗a好老婆";
//string a = "asd34ghf7asdJHYio-)00><kds";
//string b = "bsd25ghf9sasshio98s<kds";
//string a = "axjbscdd";
//string b = "sxjdkssckdge";
Console.WriteLine(a);
Console.WriteLine(b);
Program x = new Program();
x.LCS_Length(a, b);
x.Print_c(a.Length, b.Length);
x.Print_parent(a, b);
x.Print_LCS(parent, a, a.Length, b.Length);
Console.ReadLine();
}
}
}