最长公共子序列Lcs 51Nod - 1006

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main{
    static int[][] dp = new int[1010][1010];
    static int[][] pos = new int[1010][1010];
    static String a="[",b="]",tmp;
        
    public static void outPut(int i,int j){
        if(i==-1||j==-1)return;
        if(pos[i][j]==1){
            outPut(i-1,j-1);
            System.out.print(a.charAt(i));
        }
        else if(pos[i][j]==2){
            outPut(i,j-1);
        }
        else {
            outPut(i-1,j);
        }
    }
    public static void main(String[] args){
        PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        tmp = sc.next();
        a+=tmp;
        tmp = sc.next();
        b+=tmp;
        out.println(a);
        out.println(b);
        int max=0;
        boolean[] bok = new boolean[2010];
        for(int i=1;i<a.length();i++){
            for(int j = 1;j<b.length();j++){
                if(a.charAt(i) == b.charAt(j)){                   
                    dp[i][j] = dp[i-1][j-1]+1;
                    pos[i][j] = 1;
                }    
                else {
                    dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
                    if(dp[i][j-1]>dp[i-1][j])
                        pos[i][j] = 2;
                    else 
                        pos[i][j] = 3;
                }
            }
        }
         outPut(a.length()-1,b.length()-1);
    }
} 

具体如何输出字符串中的有效部分 通过每次记录相等的串的路径 然后递归输出即可
每次LCS字符串更新 都是通过公共字符更新的长度 所以就按照顺序输出此类顺序即可



猜你喜欢

转载自blog.csdn.net/qq_33859479/article/details/79889563