LeetCode训练营之字符串

最长公共子串

给定两个字符串,求最长的公共子字符串并输出

    public static String longestCommonSubString(String str1,String str2){
        StringBuilder result = new StringBuilder();
        //边界值检测
        if(str1 == null || str2 == null || str1.length() < 1 || str2.length() < 1)
            return result.toString();
        //记录字符串的长度,用于遍历以及创建二维数组
        int len1 = str1.length();
        int len2 = str2.length();
        //记录最大子串的长度
        int max = -1;
        //分别记录两个字符串的最大子串的结束字符的位置
        int end1 = -1;
        int end2 = -1;
        //创建的二维数组行数和列数要比字符串长度大一,为的是可以记住上一个位置处的字符是否相同
        int[][] lengths = new int[len1+1][len2+1];
        //遍历记录每一个字符以及该字符前的相同子串的长度
        for(int i = 1 ; i < len1 + 1 ; i++){
            for(int j = 1; j < len2 + 1 ; j++){
                if(str1.charAt(i-1) == str2.charAt(j-1)){
                    lengths[i][j] = lengths[i-1][j-1] + 1;
                    if(lengths[i][j] > max){
                        max= lengths[i][j];
                        end1 = i - 1;
                        end2 = j - 1;
                    }
                }
            }
        }
        //记录最长子串的第一个字符分别在两个字符串中的下标位置
        int begin1 = end1 - max + 1;
        int begin2 = end2 - max + 1;
        //循环添加相同字符,直至第一个不同的字符出现
        while(begin1 >= 0 && begin1 < str1.length() && begin2 >= 0 && begin2 < str2.length()){
            if(str1.charAt(begin1) == str2.charAt(begin2)){
                result.append(str1.charAt(begin1));
                begin1++;
                begin2++;
            }else{
                break;
            }
        }
        return result.toString();
    }

你可能感兴趣的:(数据结构与算法)