-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28. Implement strStr().java
More file actions
58 lines (55 loc) · 1.59 KB
/
28. Implement strStr().java
File metadata and controls
58 lines (55 loc) · 1.59 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
public class Solution {
public int strStr(String haystack, String needle) {
int[] table = KMP(needle);
int res = 0;
int index = 0;
if (needle.length() == 0) {
return 0;
}
for (int i = 0; i < haystack.length(); i++) {
if (haystack.charAt(i) == needle.charAt(index)) {
index++;
if (index == needle.length()) {
return res;
}
} else {
if (index == 0 || i == 0) {
res = i + 1;
} else {
index = table[index - 1];
if (haystack.charAt(i) == needle.charAt(index)) {
res = i - index;
index++;
} else {
index = 0;
res = i;
i--;
}
}
}
}
return -1;
}
public int[] KMP(String s) {
int len = s.length();
int[] res = new int[len];
int i = 0;
int j = 0;
while (i < len - 1) {
i++;
if (s.charAt(i) == s.charAt(j)) {
j++;
res[i] = j;
} else {
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = res[j - 1];
}
if (s.charAt(i) == s.charAt(j)) {
j++;
res[i] = j;
}
}
}
return res;
}
}