Home » Java » The longest common subsequence of Java code

The longest common subsequence of Java code

package someLearn;
/ / the longest common subsequence is when a collection of code does not say what is mainly about the size of the array should be defined as c[m+1][n+1] Z so that c[m][n] can be used to express the length of m n of the longest common subsequence
Public, class, Lcs {
Public, static, int, LCS (String, STR1, String, STR2) {
Int, m=str1.length ();
Int, n=str2.length ();
Int [][] c=new int[m+1][n+1]; / / c[i][j] Xi Yj records, length of the longest common subsequence
Int b=new int[m+1][n+1] [][];
For (int i=0; i<=m; i++) {
For (int j=0; j<=n; j++) {
If (i==0||j==0) {
C[i][j]=0;
}else if (str1.charAt (i-1) ==str2.charAt (J-1)) {
C[i][j]=c[i-1][j-1]+1;
B[i][j]=0;
}else if (c[i-1][j]>=c[i][j-1]) {
C[i][j]=c[i-1][j];
B[i][j]=1;
}else{
C[i][j]=c[i][j-1];
B[i][j]=2;
}
}
}
PrintLcs (B, STR1, m, n);
Return c[m][n];
}
Public, static, void, printLcs (int[][]b, String, STR1, int, m, int, n) {
If (m==0||n==0) {
Return;
}
If (b[m][n]==0) {
PrintLcs (B, STR1, M-1, n-1);
System.out.print (str1.charAt (m-1));
}else if (b[m][n]==1) {
PrintLcs (B, STR1, M-1, n);
}else{
PrintLcs (B, STR1, m, n-1);
}
}
Public, static, void, main (String[], args) {
String str1= "ABDCABDCA"";
String str2= "ADSBADBASDQ"";
System.out.println (LCS (STR1, STR2));
}
}

Latest