题目描述

使用动态规划算法求两个序列的最长公共子序列,需构造一条最长公共子序列。

输入

每组输入包括两行,每行包括一个字符串。

输出

两个字符序列的一条最长公共子序列。(输入已确保最长公共子序列的唯一性)

样例输入 Copy

acdbxx
ccdxx

样例输出 Copy

cdxx

package lianxi5;

import java.util.Scanner;
/*
 * 最长公共子序列
 */
public class Main18 {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		String str1=sc.nextLine();
		String str2=sc.nextLine();
		char st1[]=new char[str1.length()];
		char st2[]=new char[str2.length()];
		
		for(int i=0;i<str1.length();i++) {
			st1[i]=str1.charAt(i);
		}
		for(int i=0;i<str2.length();i++) {
			st2[i]=str2.charAt(i);
		}
		maxCommonChar(st1,st2);
	
	}
 

public static void maxCommonChar(char [] a, char [] b){  
        int m = a.length;  
        int n = b.length;  
        int [][] len = new int[m + 1][n + 1];
        int [][] flags = new int[m + 1][n + 1];
        for(int i = 0; i <= m - 1; i++){
            for(int j = 0; j <= n - 1; j++){  
                if(a[i] == b[j]){
                    len[i + 1][j + 1] = len[i][j] + 1;  
                    flags[i + 1][j + 1] = 1; 
                }else if(len[i + 1][j] >= len[i][j + 1]){  
                    len[i + 1][j + 1] = len[i + 1][j];  
                    flags[i + 1][j + 1] = 2;  
                }else{  
                    len[i + 1][j + 1] = len[i][j + 1];  
                    flags[i + 1][j + 1] = 3;  
                }  
            }  
        }  
        int k = len[m][n];
        char [] commonChars = new char[k];
        int i = m, j = n; 
        for(;i > 0 && j > 0;){  
            if(flags[i][j]==1){
                commonChars[k - 1] = a[i - 1];  
                k--;  
                i--;  
                j--;  
            }else if(flags[i][j] == 2){  
                j--; 
            }else{  
                i--;  
            }  
        }   
     
        for(int l = 0; l <= len[m][n] - 1; l++){  
            System.out.print(commonChars[l]);  
        }  
}  
}