获取两个字符串中最大相同子串

2020/08/15 111

算法

    public String getMaxSameString(String str1, String str2) {
        var arr1 = str1.toCharArray();
        var arr2 = str2.toCharArray();
        int beginIndex = 0;
        int endIndex = 0;
        int maxBeginIndex = 0;
        int maxEndIndex = 0;
        for (int i = 0; i < arr1.length; i++) {
            int bakI = i;
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    if (endIndex == i) {
                        endIndex++;
                        if (endIndex > maxEndIndex) {
                            maxBeginIndex = beginIndex;
                            maxEndIndex = endIndex;
                        }
                    } else {
                        beginIndex = i;
                        endIndex = i + 1;
                    }
                    i++;
                } else {
                    i = bakI;
                    beginIndex = 0;
                    endIndex = 0;
                }
            }
        }
        return str1.substring(maxBeginIndex, maxEndIndex);
    }