最长公共子字符串

给定两个字符串,找到最长的公共子字符串,比如String1=abc12dfe string2=abdec12dfab 所以公共子字符串为c12df。

思路:动态规划,以每个字符为尾字符。

代码:

public class Main {
    //生成dp数组
    public static int[][] getdp(char[] c1, char[] c2) {
        
        int len1 = c1.length;
        int len2 = c2.length;
        
        int[][] dp = new int[len1][len2];
        
        //第一行填充
        for(int j=0; j<len2; j++) {
            if(c1[0] == c2[j]) {
                dp[0][j] = 1;
            }
        }
        
        //第一列填充
        for(int i=0; i<len1; i++) {
            if(c1[i] == c2[0]) {
                dp[i][0] = 1;
            }
        }
        
        for(int i=1; i<len1; i++) {
            for(int j=1; j<len2; j++) {
                if(c1[i] == c2[j]) {
                    dp[i][j] = dp[i-1][j-1]+1;
                }
            }
        }
        
        return dp;
    }
    
    public static String lcs(String s1, String s2) {
        if(s1==null || s1.length()==0 || s2==null || s2.length()==0) {
            return null;
        }
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        
        int[][] dp = getdp(c1, c2);
        
        int row = dp.length;
        int col = dp[0].length;
        
        int end = 0;
        int max =0;
        for(int i=0; i<row; i++) {
            for(int j=0; j<col; j++) {
                if(dp[i][j]>=max) {
                    max = dp[i][j];
                    end = i;
                }
            }
        }
        
    return s1.substring(end-max+1,end+1);
    }
    
    public static void main(String[] args) {
        String s1 = "A1234B";
        String s2 = "CD1234";
        
        System.out.println(lcs(s1, s2));
    }
}
原文地址:https://www.cnblogs.com/loren-Yang/p/7504083.html