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); } }
最長公共子串——動態規劃
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.