【算法】LCS算法以及其JAVA的实现

LCS问题是动态规划的经典问题，同时也算作入门问题吧。其目的是要求出两个串的最长公共子串。例如如下两个串：

1.如果Xm = Yn , 那么Zk != Xm,且Zk-1 为 Xm-1 的一个LCS

2.如果Xm != Yn , 那么Zk ! = Yn ,且Zk-1 为 Yn-1的一个LCS

1.如果i=0或者j=0: c[i][j]=0,   b[i][j]=’ ‘.

2.如果i,j>0且x[i]=y[j]   c[i][j] = c[i-1][j-1] , b[i][j] = ‘x’代表上箭头

3.如果i,j>0且x[i]!=y[j]  c[i][j] = max(c[i-1][j] ,c[i-1][j-1])    b[i][j] = ‘h’ or ‘w’代表竖向箭头和横向箭头

``````private Stack<Character> stack = new Stack<Character>();
private void printLcs(char d[][], String a, int i ,int j)
{
if(i==0||j==0)
{}
else if(d[i][j]=='x')
{
stack.push(a.charAt(i-1));
printLcs(d,a,i-1,j-1);
}
else if (d[i][j]=='h')
printLcs(d,a,i-1,j);
else
printLcs(d,a,i,j-1);
}
public String getLCS(String a,String b)
{
int[][] c = new int[a.length()+1][b.length()+1];
char[][] d = new char [a.length()+1][b.length()+1];
for(int i = 0; i<=a.length();i++)
c[i][0]=0;
for(int j = 0; j<=b.length();j++)
d[0][j]=0;
for(int i = 1; i<=a.length();i++)
{
for(int j = 1; j<=b.length();j++)
{
if(a.charAt(i-1)==b.charAt(j-1))
{
c[i][j] = c[i-1][j-1]+1;	d[i][j] = 'x';
}
else if (c[i-1][j] >= c[i][j-1])
{
c[i][j] = c[i-1][j];		d[i][j] = 'h';
}
else
{
c[i][j] = c[i][j-1];		d[i][j] = 'w';
}
}
}

printLcs(d , a , a.length(),b.length());
String res = "";
while(!stack.empty())
res += stack.pop().toString();
return res;
}``````