-
Notifications
You must be signed in to change notification settings - Fork 1
/
StrStr.java
66 lines (64 loc) · 1.69 KB
/
StrStr.java
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
/**
* <a href=https://leetcode-cn.com/problems/implement-strstr/description/>
* Click to see online description
* </a>
* <br>
* Implement KMP algorithm.
* @author LBW
*/
public class StrStr {
public int strStr(String haystack, String needle) {
if (needle.equals(""))
return 0;
// get the array {next}.
int[] next = getNext(needle);
// start to traverse the string by i. (j is used to indicate index of needle)
int i = 0, j = 0;
while (i < haystack.length()) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
}
else if (j > 0) {
j = next[j-1];
}
else { // j = 0
i++;
}
if (j == needle.length()) {
return i - needle.length();
}
}
return -1;
}
/**
* Get next array.
* @param needle
* @return next
*/
private int[] getNext(String needle) {
int len = needle.length();
int[] next = new int[len];
next[0] = 0;
int i = 1, j = 0;
while (i < len) {
if (needle.charAt(i) == needle.charAt(j)) {
next[i] = j + 1;
i++;
j++;
}
else if (j == 0) {
next[i] = 0;
i++;
}
else { // j > 0
j = next[j-1]; // This step is really important! j indicates candidates of next.
}
}
return next;
}
public static void main(String[] args) {
StrStr strStr = new StrStr();
strStr.strStr("hello", "ll");
}
}