在学习KMP算法之前, 我们事先了解了一个实例
也就是暴力字符串匹配
发现了它的效率十分的底下
然后我们才了解了KMP
package suanfa10;
import java.util.Arrays;
public class KMPtest {
public static void main(String[] args) {
String str1 = "bb bsjdfbb lo isj";
String str2 = "bsjdfbb";
int[] next = getnext(str2);
System.out.println("next->"+ Arrays.toString(next));
int i = KMPfind(str1, str2, next);
System.out.println(i);
}
public static int KMPfind(String str1, String str2, int[] next){
for (int i = 0, j = 0; i < str1.length(); i++){
while( str1.charAt(i) != str2.charAt(j) && j>0){
j = next[j-1];
}
if (str1.charAt(i) == str2.charAt(j)){
j++;
}
if (j == str2.length()){
return i - (j - 1);
}
}
return -1;
}
//获得一个字符串的部份匹配值表
public static int[] getnext(String str){
int[] next = new int[str.length()];
next[0] = 0;
for (int i = 1, j = 0; i < str.length(); i++){ //j呢表示部份匹配值, 且是前缀的后一位
while( str.charAt(i) != str.charAt(j) && j>0){
j = next[j-1];
}
if ( str.charAt(i) == str.charAt(j)){
j++; //部份匹配值就要加1;
}
next[i] = j;
}
return next;
}
}
next->[0, 0, 0, 0, 0, 1, 1]
3
这样直观的一比较就可以十分清晰的看到
KMP比起暴力匹配的好处就是
- i 一直就在++
- j有可能不用从0再开始