给定两个序列X,Y,求最长公共子序列。
- /**
- * Dynamic Programming, DP
- *
- */
- public class DPLCS {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String x = "abcbdab";
- String y = "bdcaba";
- String cls = "bdab";
- DPLCS dp = new DPLCS(x.toCharArray(),y.toCharArray());
- System.out.println(dp.getDPLCSLength());
- System.out.println(dp.getDPLCS());
- }
- private int[][] c = null;
- private int[][] b = null;
- private char[] x = null;
- private char[] y = null;
- private int lcsLength;
- private char[] lcs;
- public DPLCS(char[] x, char[] y, int m, int n){
- c = new int[m+1][n+1];
- b = new int[m+1][n+1];
- for (int i = 0; i < m+1; i++) c[i][0]=0;
- for (int j = 0; j < n+1; j++) c[0][j]=0;
- this.x = x;
- this.y = y;
- dpLcs(x, y, m, n);
- lcs = new char[lcsLength];
- //生成公共子序列
- genLCS(m, n, lcsLength-1);
- }
- public DPLCS(char[] x, char[] y){
- this(x, y, x.length, y.length);
- }
- private void dpLCS(char[] x, char[] y, int m, int n) {
- // TODO Auto-generated method stub
- for (int i = 1; i < m+1; i++) {
- for (int j = 1; j < n+1; j++) {
- if(x[i-1]==y[j-1]){//注意index
- c[i][j]=c[i-1][j-1]+1;
- b[i][j]=1;//表示由子问题i-1,j-1得来
- }else{
- if(c[i][j-1]>=c[i-1][j]){
- c[i][j]=c[i][j-1];
- b[i][j]=2;//表示由子问题i,j-1得来
- }
- else{
- c[i][j]=c[i-1][j];
- b[i][j]=3;//表示由子问题i-1,j得来
- }
- }
- }
- }
- lcsLength = c[m][n];
- }
- private void genLCS(int i, int j, int index) {
- // TODO Auto-generated method stub
- if(index<0)
- return;
- if(b[i][j]==1){
- lcs[index]= x[i-1];
- genLCS(i-1,j-1,index-1);
- }
- else if(b[i][j]==2)
- genLCS(i,j-1,index);
- else
- genLCS(i-1,j,index);
- }
- public int getDPLCSLength(){
- return lcsLength;
- }
- public char[] getDPLCS(){
- return lcs;
- }
- }
缺陷:最长公共子序列可能有多条,该程序只求出其中一条