数据结构--KMP算法(字符串匹配算法)--在末尾添加字符串,是其包含字符串两次,且长度最短

在末尾添加字符串,使其包含字符串两次,且长度最短

* 找出字符串的next数组,然后添加的部分就是字符串的最后一个字符的next值到最后一个位置的值,这是最大前缀和最大后缀相等的地方
* 注意这里要找的是字符串中后面字符和前面字符匹配的最长位置,所以这里的 next.length = str.length() + 1

public class ShortestHaveTwice {
    public static String shortestHaveTwice(String str){
        int[] next = nextArray(str);
        System.out.println(next[str.length()]);
        return str + str.substring( next[str.length()] );
    }

    private static int[] nextArray(String str) {
        if(str == null || str.length() == 0) return null;

        int[] next = new int[str.length() + 1];
        next[0] = -1;
        next[1] = 0;
        int num = 0;
        int index = 2;
        while(index < next.length){
            if(str.charAt( index - 1 ) == str.charAt( num )){
                next[index++] = ++num;
            } else if(num > 0){
                num = next[num];
            } else{
                next[index++] = 0;
            }
        }
        return next;
    }

    public static void main(String[] args){
        String s = shortestHaveTwice("ababaas");
        System.out.println(s);
    }
}

  

posted @ 2018-05-03 09:48  SkyeAngel  阅读(196)  评论(0编辑  收藏  举报