zoukankan      html  css  js  c++  java
  • 查找子串KMP实现

    参考: KMP算法详解-彻底清楚了(转载+部分原创)

    KMP算法求next,用动态规划思想去理解

    求next数组,利用①回溯的方法、②动态规划思路、③最长相等真前后缀减少回溯的方法

    典范代码:

    public int[] getNext(String p){
            int[] next = new int[p.length()];//p的最后一个元素不需要计算,用不到
            int j = 0;
            int k = -1;
            next[0] = -1;
            while(j<p.length()-1){
                if(k==-1||p.charAt(j)==p.charAt(k)){
                    next[++j] = ++k;
                }else{
                    k = next[k];
                }
            }
            return next;
        }
    public int indexOf(String s,String p){
            int m = s.length(),n = p.length();
            int i=0,j=0;
            int[] next = getNext3(p);
            while(i<m&&j<n){
                if(j==-1||s.charAt(i)==p.charAt(j)){
                    i++;j++;
                }else{
                    j = next[j];
                }
            }
            return j==n?i-j:-1;
        }
     
  • 相关阅读:
    spoj705
    bzoj2440
    spoj220
    bzoj2301
    hdu1695
    poj3294
    hdu3518
    poj3693
    函数
    样式
  • 原文地址:https://www.cnblogs.com/tonghaolang/p/15323216.html
Copyright © 2011-2022 走看看