Skip to content

Commit a6a4bb7

Browse files
committed
KMP
1 parent 742ff52 commit a6a4bb7

File tree

2 files changed

+75
-1
lines changed

2 files changed

+75
-1
lines changed

src/ImplementstrStr/Solution.java

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package ImplementstrStr;
2+
3+
/**
4+
* User: Danyang
5+
* Date: 1/29/2015
6+
* Time: 19:26
7+
*
8+
* Implement strStr().
9+
10+
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
11+
*/
12+
public class Solution {
13+
/**
14+
* KMP
15+
*
16+
* Notice:
17+
* 1. build a table of the length of matched prefix_suffix - PREFIX SUFFIX LENGTH TABLE
18+
* 2. test case "mississippi", "issip"; "redoredoreo", "redoreo"
19+
* 3. S[i+j]
20+
* @param haystack
21+
* @param needle
22+
* @return
23+
*/
24+
public int strStr(String haystack, String needle) {
25+
if(haystack.length()<needle.length())
26+
return -1;
27+
if(needle.length()<=1)
28+
return haystack.indexOf(needle);
29+
30+
char[] S = haystack.toCharArray();
31+
char[] W = needle.toCharArray();
32+
// build prefix_suffix_length_table
33+
int[] T = new int[W.length+1];
34+
T[0] = -1;
35+
T[1] = 0;
36+
int i = 0;
37+
int j;
38+
for(j=1; j<W.length; ) {
39+
if(W[i]==W[j]) {
40+
T[j+1] = i+1;
41+
i++;
42+
j++;
43+
}
44+
else if(i!=0) { // reredo...rerereply
45+
i = T[i];
46+
}
47+
else {
48+
T[j+1] = 0;
49+
j++;
50+
}
51+
}
52+
53+
// search
54+
i = 0;
55+
j = 0;
56+
while(i+j<S.length) {
57+
if(S[i+j]==W[j]) {
58+
j++;
59+
if(j==W.length)
60+
return i;
61+
}
62+
else {
63+
if(T[j]!=-1) {
64+
i = i+j-T[j];
65+
j = T[j];
66+
}
67+
else {
68+
i += 1;
69+
j = 0;
70+
}
71+
}
72+
}
73+
return -1;
74+
}
75+
}

src/SubstringwithConcatenationofAllWords/Solution.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ public List<Integer> findSubstring(String S, String[] L) {
5757
workingWin.clear();
5858
win_e = -1;
5959
Lmap = new HashMap<>(Lmap_origin);
60-
continue;
6160
}
6261
}
6362

0 commit comments

Comments
 (0)