Original title URL: https://leetcode.com/problems/implement-strstr/
Implement Strstr ().
Returns the index of the occurrence of needle in haystack, or-1 if needle isn't part of haystack.
Method one: Poor lift.
public class Solution {public
int strstr (String haystack, string needle) {
if (needle.length () = 0) return 0;
if (Haystack.length () < Needle.length ()) return-1;
char[] ha = Haystack.tochararray ();
char[] na = Needle.tochararray ();
for (int i = 0; i < ha.length && i + na.length <= ha.length; i++) {
Boolean match = true;
for (int j = 0; J < Na.length; J +) {
if (ha[i + j]!= Na[j]) {
match = false;
break;
}
}
if (match) return i;
}
Return-1
}
}
Method two: KMP algorithm.
public class Solution {public
int strstr (String haystack, string needle) {
char[] ha = Haystack.tochararray ();
char[] na = Needle.tochararray ();
int[] KMP = new Int[na.length];
for (int offset=math.min (na.length-1, ha.length-na.length); offset>0; offset--) {for
(int i=0; i+offset< Na.length; i++) {
if (Na[i]!= Na[i+offset]) {
Kmp[i+offset] = offset;
break;
}
}} int h = 0, n = 0;
while (H + na.length <= ha.length && N < na.length) {
if (ha[h+n] = = Na[n]) {
n + +;
} else if (Kmp[n] = = 0) {
H = + n + 1;
n = 0;
} else {
h = kmp[n];
N-= Kmp[n];
}
if (n = = na.length) return h;
}
return n = = na.length? H:-1;
}
}
Another implementation:
public class Solution {public int strstr (String haystack, string needle) {if (needle.length () = 0) return 0
;
if (Haystack.length () < Needle.length ()) return-1;
char[] ha = Haystack.tochararray ();
char[] na = Needle.tochararray ();
int[] KMP = new Int[na.length]; for (int i = Math.min (Ha.length-na.length, na.length-2); I >= 1; i--) {for (int j = i; J < Na.length -1;
J + +) {if (na[j-i] = = Na[j]) {kmp[j + 1] = i;
} else {break;
} int h = 0, n = 0;
while (H + na.length <= ha.length) {if (ha[h + n] = = Na[n]) {n++;
if (n = = na.length) return h;
else if (kmp[n] = = 0) {H + = Math.max (n, 1);
n = 0;
else {h = kmp[n];
N-= Kmp[n];
} } return-1; }
}
There is a very cow KMP algorithm introduction, reference: http://blog.csdn.net/v_july_v/article/details/7041827
After looking at the above, it is easy to understand that the KMP array is considered to be the length of the largest public prefix.
public class Solution {public
int strstr (String haystack, string needle) {
if (needle.length () = 0) return 0;
if (Haystack.length () < Needle.length ()) return-1;
char[] ha = Haystack.tochararray ();
char[] na = Needle.tochararray ();
int[] len = new Int[na.length];
for (int i = 1; i < na.length && i <= ha.length-na.length; i++) {
int j = len[i-1];
while (J > 0 && na[j]!= na[i]) j = len[j-1];
Len[i] = j + (Na[j]==na[i]? 1:0);
int h = 0, n = 0;
while (H + na.length <= ha.length) {
if (ha[h + n] = = Na[n]) {
n++;
if (n = = na.length) return h;
} else if (n = = 0) {
h++;
} else {
H + = n-len[n-1
]; n = len[n-1];
}
Return-1
}
}