# 算法 || KMP #

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。


步骤:①寻找前缀后缀最长公共元素长度

   ②求next数组 

   ③根据next数组进行匹配 

————2020.1.17———— 随笔 第1张

失配时,模式串向右移动的位数为:失配字符所在位置 - 失配字符对应的next 值,即j - next[j]。

 递推求next数组。

 1 public static int[] getNext(String str) {
 2     int[] next = new int[str.length()];
 3     next[0] = -1;
 4     int i = 1, curMatch = 0;
 5     while (i<str.length()-1) {
 6         if (str.charAt(i) == str.charAt(curMatch)) {
 7             next[i+1] = next[i] + 1;
 8             curMatch++;
 9         } else {
10             next[i+1] = 0;
11             curMatch = 0;
12         }
13         i++;
14     }
15     return next;
16 }

next数组与有限自动机。

————2020.1.17———— 随笔 第2张

 

 

next数组的优化。

————2020.1.17———— 随笔 第3张

 

KMP。

 1 public static int KMP(String s, String t) {
 2     int[] next = getNext(t);
 3     int i = 0, j = 0;
 4     while (i < s.length() && j<t.length()) {
 5         if (j == -1 || s.charAt(i) == t.charAt(j))  
 6         {  
 7             i++;  
 8             j++;  
 9         }  
10         else  
11         {      
12             j = next[j];  
13         }  
14     }
15     if (j == t.length()) 
16         return i - j ;
17     else 
18         return -1;
19 }

BM、Sunday算法等待补充。。

# Edit : 2020.1.17

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄