-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKMP.java
More file actions
103 lines (77 loc) · 1.97 KB
/
KMP.java
File metadata and controls
103 lines (77 loc) · 1.97 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
public class KMP {
/* 参考理论:
* 1,http://www.ics.uci.edu/~eppstein/161/960227.html
* 2,http://www.ics.uci.edu/~goodrich/dsa/11strings/demos/pattern/
*/
/* 参考代码:
* 1,http://www.cs.princeton.edu/algs4/53substring/KMP.java.html
* 2,http://wansishuang.javaeye.com/blog/402018
*/
// 构建DFA
public int[] overlap(String pattern){
int[] next = new int[pattern.length()];
next[0] = 0;
next[1] = 0;
int i = 2;
int cur = 0;
while (i < pattern.length()) {
if (pattern.charAt(i-1)==pattern.charAt(cur)) { // 当前匹配,移到下一个位置
next[i] = cur+1;
cur++;
i++;
}
else if (cur > 0) { // cur > 0,匹配了一部分,回溯
cur = 0;
// cur = next[cur]; // 有的人这样来回溯
}
else{ // cur=0,当前不匹配
next[i] = 0;
i++;
}
}
return next;
}
// 根据DFA进行查找
public int search(String source,String pattern){
int[] next = this.overlap(pattern);
for (int i = 0; i < next.length; i++) {
System.out.print(pattern.charAt(i) + " ");
}
System.out.println();
for (int i = 0; i < next.length; i++) {
System.out.print(next[i] + " ");
}
System.out.println();
int j = 0;
for (int i = 0; i < source.length(); i++) {
for(;;){
if (source.charAt(i) == pattern.charAt(j)) {
j++;
if (j == pattern.length()) { // 找到一个匹配
return i-j+1;
}
break;
}
else if (j == 0) { // 没有与source[i]的匹配,直接让i+1
break;
}
else { // 匹配了一部分失败,按next数组,让j回溯
j = next[j];
}
}
}
return -1;
}
public static void main(String[] args) {
KMP kmp = new KMP();
String source = "sfababcasfbabcabcabababcabababbabcab";
String pattern = "abababb";
int index = kmp.search(source, pattern);
if(index >= 0){
System.out.println(index);
}
else{
System.out.println("No contain");
}
}
}