最长公共子串

 

思路参考:最长公共子序列

public class Solution {
    /**
     * longest common substring
     * @param str1 string字符串 the string
     * @param str2 string字符串 the string
     * @return string字符串
     */
    public static String LCS(String str1, String str2) {
        if (str1 == null || str2 == null || str1.equals("") || str2.equals("")) {
            return "";
        }
        str1 = " " + str1;
        str2 = " " + str2;
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();
        int maxlen = 0;
        int maxi=0;
        int[][] dp = new int[str1.length()][str2.length()];

        for (int i = 1; i < str1.length(); i++) {
            for (int j = 1; j < str2.length(); j++) {
                if (chars1[i] == chars2[j]) {
                    if (chars1[i - 1] != chars2[j - 1]) {
                        dp[i][j] = 1;
                    } else {
                        dp[i][j] = dp[i - 1][j - 1] + 1;
                    }
                } else {
                    dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
                }
                if (maxlen<dp[i][j]){
                    maxlen = dp[i][j];
                    maxi = i;
                }
            }
        }
        if (maxlen == 0){
            return "-1";
        }
        return str1.substring(maxi-maxlen+1,maxi+1);
    }
}

 

posted @ 2020-10-07 19:48  Adom_ye  阅读(109)  评论(0编辑  收藏  举报