- package com.eshore.sweetop.dynamicprogramming;
- public class LCS {
- public static void LCSLength(char[] x, char[] y) {
- int m = x.length;
- int n = y.length;
- int[][] c = new int[m + 1][n + 1];
- char[][] b = new char[m + 1][n + 1];
- for (int i = 1; i <= m; i++) {
- c[i][0] = 0;
- }
- for (int i = 1; i < n; i++) {
- c[0][i] = 0;
- }
- for (int i = 1; i <= m; i++) {
- for (int j = 1; j <= n; j++) {
- if (x[i-1] == y[j-1]) {
- c[i][j] = c[i - 1][j - 1] + 1;
- b[i][j] = '※';
- } else if (c[i - 1][j] >= c[i][j - 1]) {
- c[i][j] = c[i - 1][j];
- b[i][j] = '↑';
- } else {
- c[i][j]=c[i][j-1];
- b[i][j]='←';
- }
- }
- }
- display(b,x,m,n);
- }
- public static void display(char[][] b,char[] x,int i,int j){
- if(i==0 || j==0){
- return;
- }
- if(b[i][j]=='※'){
- display(b,x,i-1,j-1);
- System.out.print(x[i-1]);
- }else if(b[i][j]=='↑'){
- display(b,x,i-1,j);
- }else{
- display(b,x,i,j-1);
- }
- }
- public static void main(String[] args) {
- char[] a={'A','B','C','B','D','A','B'};
- char[] b={'B','D','C','A','B','A'};
- LCS.LCSLength(a, b);
- System.out.println();
- LCS.LCSLength(b, a);
- }
- }
算法之LCS
最新推荐文章于 2022-03-18 14:26:20 发布