-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
63 lines (60 loc) · 1.55 KB
/
Solution.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
// method 1: brute force
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length();
int m = needle.length();
if (m == 0){
return 0;
}
int i = 0, j = 0;
while (i < n && j < m){
if (haystack.charAt(i) == needle.charAt(j)){
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
return (i - j <= n -m)? (i - j): -1;
}
}
// method 2: KMP
class Solution {
private int[] createNext(String p){
int m = p.length();
int[] next = new int[m];
next[0] = -1;
int t = -1, j = 0;
while (j < m - 1){
if ( t < 0 || p.charAt(j) == p.charAt(t)){
next[++j] = ++t;
} else {
t = next[t];
}
}
return next;
}
public int strStr(String haystack, String needle) {
int n = haystack.length();
int m = needle.length();
if (m == 0){
return 0;
}
int[] next = createNext(needle);
int i = 0, j = 0;
while (i < n && j < m){
if (haystack.charAt(i) == needle.charAt(j)){
i++;
j++;
} else {
if (j == 0){
i++;
} else {
j = next[j];
}
}
}
return (j == m)? (i - j): -1;
}
}