Originally is a very simple question, the big God uses the five elements code to fix, I have to use 40 lines of code, but just realize the next KMP algorithm, is also a kind of study.
The topics are as follows:
In fact, is a string matching problem, match to where, on the output where the subscript, otherwise output-1. When I saw this topic, I thought of the KMP algorithm, originally thought to save time and effort, did not think the calculation is quite slow. The Java implementation KMP algorithm is solved as follows:
Find next array public int[] Makenext (String P) {int q,k;
int[] Next = new Int[p.length ()];
Next[0] = 0;
for (q = 1,k = 0; q < p.length (); ++q) {while (k > 0 && p.charat (q)!= P.charat (k))
k = Next[k-1];
if (P.charat (q) = = P.charat (k)) k++;
NEXT[Q] = k;
return to Next; //Returns the value of each move public int get_step (String haystack, string Needle,int next[],int count) {if haystack.substring (count,
Needle.length () +count). Equals (needle)) return-1;
for (int i = Needle.length (); i>0;i--) {if (Haystack.substring (count, I+count). Equals (needle.substring (0, I))
Return needle.substring (0, I). Length ()-next[i-1];
return 1; }//Main function, enter two string, return matching first subscript public int strstr (String haystack, string needle) {if (Haystack.equals ("") &&needle.
Equals ("")) return 0;
if (Needle.equals ("")) return 0; if (Haystack.length () <needle.length ()) return-1;
int count=0,step = 0;;
int[] Next = makenext (needle);
while (Count<=haystack.length ()-needle.length ()) {step = Get_step (haystack, needle, next,count);
if (step!=-1) count+=step;
else return count;
} return-1; }