最长公共子串/动态规划实现

来源:互联网 发布:pc视频编辑软件 编辑:程序博客网 时间:2024/06/07 00:17

两字符串 求取最长公共子串

例如:

 abcdef 

hghcdefgh =>cdef

package practice2;import java.util.*;/*最长公共子串ABCDEQADEFGHreturn DE*/public class LargestSubString {public static void main(String[] args) {Scanner input = new Scanner(System.in);largestSubString(input.next(),input.next());}public static void largestSubString(String s1,String s2) {int L1 = s1.length();int L2 = s2.length();/*dp[i][j] 如果把A[i] B[j]当作公共子串最后一个字符时其长度A = "ABCDEQ"B = "ADEFGH"dp[0][0] = 1;   dp[0][0] = 1;dp[0][1] = 0;dp[1][0] = 0;dp[0][2] = 0;dp[2][0] = 0;dp[4][2] = 2;dp[i][j] = 0  A[i] != B[j];  dp[i-1][j-1] + 1 */int[][] dp = new int[L1][L2];int max = 0;int bestS1I = 0;for(int i = 0;i < L1;i++) {for(int j = 0;j < L2;j++) {/* * 如果两个序列空串 那么公共子串就是0 */if(i == 0 || j == 0) {if(s1.charAt(i) == s2.charAt(j)) {dp[i][j] = 1;} else {dp[i][j] = 0;}} else {/* * dp[i][j] 如果把A[i] B[j]当作公共子串最后一个字符时其长度 * 当A[i]=B[j] 说明当前字符作为公共子串的最后一个字符时,当前子串的长度取决于前面子串的长度 */if(s1.charAt(i) == s2.charAt(j)) {dp[i][j] = dp[i-1][j-1] + 1;} else {dp[i][j] = 0;}}if(dp[i][j] > max) {max = dp[i][j];bestS1I = i;}}}System.out.println(s1.substring(bestS1I-max+1,bestS1I+1));for(int i = 0;i < L1;i++) {for(int j = 0;j < L2;j++) {if(j == L2-1) {System.out.println(dp[i][j]);} else {System.out.print(dp[i][j]+" ");}}}}}