KMP算法浅析

具体参见: KMP算法详解

背景

  KMP算法之所以叫做KMP算法是因为这个算法是由三个人共同提出来的,就取三个人名字的首字母作为该算法的名字。其实KMP算法与BF算法的区别就在于KMP算法巧妙的消除了指针i的回溯问题,只需确定下次匹配j的位置即可,使得问题的复杂度由O(mn)下降到O(m+n)

  KMP算法的思想就是:在匹配过程称,若发生不匹配的情况,如果next[j]>=0,则目标串的指针i不变,将模式串的指针j移动到next[j]的位置继续进行匹配;若next[j]=-1,则将i右移1位,并将j置0,继续进行比较。
  在KMP算法中,为了确定在匹配不成功时,下次匹配时j的位置,引入了next[]数组,next[j]的值表示P[0...j-1]中最长后缀的长度等于相同字符序列的前缀。
对于next[]数组的定义如下:
  1) next[j]=-1  j=0
  2) next[j]=max k:0<k<j P[0...k-1]=P[j-k,j-1]
  3) next[j]=0  其他
如:
  P      a    b   a    b   a
  j       0   1    2   3   4
  next -1  0    0   1   2
即next[j]=k>0时,表示P[0...k-1]=P[j-k,j-1]

next的求解程序如下:

  

 private int[] next(String str){
if(str == null || str.length() == 0){
return null ;
}
int [] next = new int [str.length()] ;
next[0] = -1 ;
int lastSame = 0 ;
for(int i = 1 ; i < str.length() ; i++ ){
char temp = str.charAt(i) ;
next[i] = lastSame ;
if(temp == str.charAt(lastSame)){
lastSame++ ;
}else{
lastSame = 0 ;
}
} return next ;
}

通过next采用KMP算法判断是否匹配的代码如下:

 /**
* 若src包含dest子串,则返回src中dest子串出现的位置(首字符的位置),
* 若不包含,则返回-1
* @param src
* @param dest
* @return
*/
private int KMPmatch(String src, String dest){
if(src == null || dest == null || src.length() < dest.length()){
return -1 ;
}
int [] next = next(dest);
int i = 0 ;
int j = 0 ;
while(i < src.length()){
if((j == -1) || (src.charAt(i) == dest.charAt(j))){
i++ ;
j++ ;
}else{
j = next[j] ;
} if(j == (dest.length())){
return i-j ;
}
} return -1 ;
}

  

上一篇:初识 JShell


下一篇:TestDisk 恢复rm -rf 的文件