最近学到的算法,kmp查找,看了别的大佬代码跟着写的
KMP查找算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
import java.util.Arrays;
public class getstr {
public static void main(String[] args) {
String txt = "qwertyqwertyuisdgfsdnhjt";
String gol = "sdgfsdn";
int i = kmp(txt,gol);
System.out.println("matchPoint: " + i);
}
static int kmp(String str1, String str2){
int [] ary =getnext(str2);
System.out.println(Arrays.toString(ary));
for(int i =0,j = 0; i < str1.length();i++){
while(j > 0 && str1.charAt(i) != str2.charAt(j) ){
j = ary[j-1];
}
if(str1.charAt(i) == str2.charAt(j)){
j++;
}
if(j == str2.length()){
// System.out.println("i = "+i+"\nj = "+j);
return i-j+1;
}
}
return -1;
}
static int [] getnext(String str2){
int [] ary = new int[str2.length()];
ary[0] = 0;
for(int i = 1, y = 0; i < str2.length(); i++ ){
while(y > 0 && str2.charAt(i) != str2.charAt(y)){
y-=1;
}
if(str2.charAt(i) == str2.charAt(y)){
y++;
}
ary[i] = y;
}
return ary;
}
}
|
其实一开始我也没有咋明白,但是后来我找到了下面这个文章 smoke_zl_图解kmp算法-通俗易懂kmp算法
我就一下捂了,这个查找算法太妙了,就靠这一个数组,就可以实现快速查找不回溯