-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSunday.java
More file actions
66 lines (45 loc) · 1.17 KB
/
Sunday.java
File metadata and controls
66 lines (45 loc) · 1.17 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
public class Sunday {
// 只针对所有ascii码的情况
private final static int ASSIZE = 256;
public int[] preProcess(String pattern){
int m = pattern.length();
int[] next = new int[ASSIZE];
for (int i = 0; i < ASSIZE; i++) {
next[i] = m + 1;
}
for (int i = 0; i < m; i++) {
next[pattern.charAt(i)] = m - i;
}
return next;
}
public int indexOf(String source,String pattern){
int[] next = preProcess(pattern);
int index = 0;
while (index + pattern.length() <= source.length()) {
int cur = index + pattern.length() - 1;
int m = pattern.length()-1;
for (;
m >= 0 &&
source.charAt(cur) == pattern.charAt(m);
m--,cur--){
}
if (m == -1) { //找到一个匹配
return index;
}
index += next[source.charAt(index+pattern.length())];
}
return -1;
}
public static void main(String[] args) {
Sunday sunday = new Sunday();
String source = "sfababcasfbabcabcabababcabababbabcabg";
String pattern = "abc";
int index = sunday.indexOf(source, pattern);
if(index >= 0){
System.out.println(index);
}
else{
System.out.println("No contain");
}
}
}