This is common and frequently used, and is also the subject of my exam yesterday.
Matching strings can only be compared from the first character.
Int stringindex (const char * pstr, const char * psubstr, int NPOs) <br/>{< br/> int nlen = strlen (pstr ); <br/> int nsublen = strlen (psubstr); <br/> int I = NPOs; <br/> Int J = 0; <br/> while (I <nlen & J <nsublen) <br/> {<br/> If (pstr [I] = psubstr [J]) <br/>{< br/> I ++; j ++; // continue comparison <br/>}< br/> else <br/>{< br/> I = I-j + 2; j = 1; // rollback, rematch <br/>}< br/> If (j = nsublen) <br/>{< br/> return I-j; <br/>}< br/> else <br/> {<br/> return-1; <br/>}</P> <p> int _ tmain (INT argc, _ tchar * argv []) <br/>{< br/> int nret = stringindex ("abcdefghijk", "ijk", 0); <br/> printf ("% d", nret ); <br/> getchar (); <br/> return 0; <br/>}
This algorithm can easily match the position of the child string in the parent string.
However, a lot of rollback operations are unnecessary. If the parent string is abcabcd, check the child string ABCD first from a and find that the after the first C is incorrect, it is obviously unnecessary to start from the first B of the parent string. In this case, the string can be matched directly from a after the first C.
This improved algorithm is the time complexity of this algorithm discovered by two cow workers is O (m + n ).
Although this algorithm seems not difficult, it is not easy to implement. After reading the book, these are all textbooks on data structures and algorithms.
I read n articles, that is, I did not write code independently.
When writing, it is really hard to write.