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);
        }
    }
    

      

  • 相关阅读:
    leetcode 子集
    leetcode 1111. 有效括号的嵌套深度
    leetcode289 生命游戏
    关于三次握手和四次挥手,发送方和接收方处于的状态的问题。
    面试题:随意取数
    2020/3/31
    01背包和完全背包
    USACO Agri-Net 3.1
    mfc小计
    static 成员小记
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8983912.html
Copyright © 2011-2022 走看看