zoukankan      html  css  js  c++  java
  • 数据结构--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);
        }
    }
    

      

  • 相关阅读:
    element表格添加序号
    ZOJ 3822 Domination(概率dp)
    HDU 3037(Lucas定理)
    HDU 5033 Building(单调栈维护凸包)
    HDU 5037 Frog(贪心)
    HDU 5040 Instrusive(BFS+优先队列)
    HDU 5120 Intersection(几何模板题)
    HDU 5115 Dire Wolf(区间dp)
    HDU 5119 Happy Matt Friends(dp+位运算)
    C++ string详解
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8983912.html
Copyright © 2011-2022 走看看