最长公共子串――动态规划

package com.java.study;
import java.util.Scanner;
public class MaxStr {
    public static void dp(char[]ch1, char[]ch2){
        int len1 = ch1.length;
        int len2 = ch2.length;
        int max = 0;
        int maxPos = 0;
        int [] c = new  int[len2];
        for(int i = 0 ; i < len1 ;i++){
            for(int j = len2-1 ; j >=0 ;j--){
                if(ch1[i] == ch2[j]){
                    if(i==0 || j==0){
                        c[j] = 1;
                    }else
                        c[j] = c[j-1]+1;
                    if(c[j] > max){
                        max = c[j];
                        maxPos = i;
                    }
                }else{
                    c[j] = 0;
                }
            }
        }
        System.out.println(max);
        for(int i = maxPos-max+1; i<=maxPos ;i++){
            System.out.print(ch1[i]);
        }
    }
       
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.nextLine();
        String str2 = sc.nextLine();
        char[] ch1 = str1.toCharArray();
        char[] ch2 = str2.toCharArray();  
        dp(ch1, ch2);
    }
}


你可能感兴趣的:(动态规划,最长公共子串,lcs)