最长重复字串

package Test;

public class MaxString{
    /**
     * find longest common sequence from two input string
     * @param s1
     * @param s2
     * @return length of longest common sequence
     */
    public static int LCS(String s1, String s2) {
        int[][] c = new int[s1.length()][s2.length()];

        // initialize the elements without top left element
        for(int i=0; i<s1.length();i++){
            if (s1.charAt(i) == s2.charAt(0)) {
                c[i][0] = 1;
            }
        }
//        sa nar
//        0 0 0
//        0 1 0


        for(int j = 0; j<s2.length();j++){
            if (s1.charAt(0) == s2.charAt(j)) {
                c[0][j] = 1;
            }
        }
//        sa nar
//        0 0 0
//        0 1 0
        for (int i = 1; i < s1.length(); i++) {
            for (int j = 1; j < s2.length(); j++) {

                if (s1.charAt(i) == s2.charAt(j)) {

                    c[i][j] = c[i - 1][j - 1] + 1;

                } else if (c[i][j - 1] > c[i - 1][j]) {
                    c[i][j] = c[i][j - 1];
                } else {
                    c[i][j] = c[i - 1][j];
                }
            }
        }
        return c[s1.length() - 1][s2.length() - 1];
    }



    // 求解字符串中的最长重复子串
    public static String maxRepat(String input) {
        // 参数检查
        if (input == null || input.length() == 0) {
            return null;
        }
        // 重复子串的最长长度
        int max = 0;
        // 最长重复子串的起始位置
        int first = 0;
        int k = 0;
        for (int i = 1; i < input.length(); i++) {
            for (int j = 0; j < input.length() - i; j++) {
                if (input.charAt(j) == input.charAt(i + j)) {
//              hellowdhelloko      0 = 1    1 = 2   2 = 3   3 = 4
//                    0 = 2 1= 3 2 = 4 3 = 5
//                    0 = 3
                    k++;
                } else {
                    k = 0;
                }
                if (k > max) {
                    max = k;
                    first = j - k + 1;
                }
            }
        }
        if (max > 0) {
            System.out.println(max);
            return input.substring(first, first + max);
        }
        return null;
    }

    public static void main(String[] args) {
        String str1 = "hellowdhelloko";
        String result = MaxString.maxRepat(str1);
        System.out.println(result);
        int s = MaxString.LCS("helldc","lohellc");
        System.out.print(s);

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值