forked from walnutown/CodingInTheDeep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementStrStr.java
More file actions
97 lines (92 loc) · 2.8 KB
/
Copy pathImplementStrStr.java
File metadata and controls
97 lines (92 loc) · 2.8 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
// Submission Result: Wrong Answer
// Input: "mississippi", "issipi"
// Output: "ssippi"
// Expected: null
public class Solution {
public String strStr(String haystack, String needle) {
// KMP alogrithm, O(n + m)
if (needle == null || haystack == null)
return null;
if (needle.length() == 0)
return haystack;
// needle.length() > 0 ,here
if (haystack.length() == 0)
return null;
int[] kmp_tb = new int[needle.length()];
buildKMPTable(needle, kmp_tb);
int i = 0, j = 0;
while (i + j < haystack.length()){
if (haystack.charAt(i+j) == needle.charAt(j)){
if (j == needle.length()-1)
return haystack.substring(i);
j++;
}else{
i = i + j - kmp_tb[j];
j = kmp_tb[j] > -1 ? kmp_tb[j] : 0;
}
}
return null;
}
public void buildKMPTable(String needle, int[] kmp_tb){
kmp_tb[0] = -1;
int pos = 1, cnd = 0;
while (pos < needle.length()){
if (needle.charAt(pos-1) == needle.charAt(cnd)){
kmp_tb[pos] = cnd;
cnd++;
pos++;
}else if (cnd > 0){
cnd = kmp_tb[cnd];
}else{
kmp_tb[pos] = 0;
pos++;
}
}
}
}
// Accepted, Dec 24
public class Solution {
public String strStr(String haystack, String needle) {
// KMP alogrithm, O(n + m)
if (needle == null || haystack == null)
return null;
if (needle.length() == 0)
return haystack;
// needle.length() > 0 ,here
if (haystack.length() == 0)
return null;
int[] kmp_tb = new int[needle.length()];
buildKMPTable(needle, kmp_tb);
int i = 0, j = 0;
while (i + j < haystack.length()){
if (haystack.charAt(i+j) == needle.charAt(j)){
if (j == needle.length()-1)
return haystack.substring(i);
j++;
}else{
i = i + j - kmp_tb[j];
j = kmp_tb[j] > -1 ? kmp_tb[j] : 0;
}
}
return null;
}
public void buildKMPTable(String needle, int[] kmp_tb){
kmp_tb[0] = -1;
if (needle.length() <= 1) // notice here
return;
kmp_tb[1] = 0;
int pos = 2, cnd = 0;
while (pos < needle.length()) {
if (needle.charAt(pos - 1) == needle.charAt(cnd)) {
cnd++;
kmp_tb[pos] = cnd;
pos++;
} else if (cnd > 0) {
cnd = kmp_tb[cnd];
} else {
kmp_tb[pos] = 0;
pos++;
}
}
}
}