forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmp.java
More file actions
executable file
·40 lines (37 loc) · 1001 Bytes
/
kmp.java
File metadata and controls
executable file
·40 lines (37 loc) · 1001 Bytes
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
public class Solution {
public String strStr(String haystack, String needle) {
// Start typing your Java solution below
// DO NOT write main() function
if(needle.length()==0){
return haystack;
}
int next[] = new int[needle.length()];
int j=0;
int t = -1;
next[0] =-1;
while(j<needle.length()-1){
if(t<0 || needle.charAt(j)==needle.charAt(t)){
j++;
t++;
next[j]=t;
}
else{
t=next[t];
}
}
t=0;
j=0;
while(t<needle.length() && j< haystack.length() ){
if(t<0 || needle.charAt(t)==haystack.charAt(j) ){
t++;
j++;
}else{
t=next[t];
}
}
if(t==needle.length())
return haystack.substring(j-t);
else
return null;
}
}