(reprinted from a friend's blog http://blog.csdn.net/msdnwolaile/article/details/51287911#comments)
Read a lot about the KMP algorithm books and materials, the total feeling did not say very clearly, why the next array, why give a short program, there is no process, and some posts although the next and string matching is very clear, but some of the process of reasoning is quite complex, more abstract, Today, here is a simple mention of my understanding, as far as possible to make this process simple, easy to understand
From the beginning of the pattern matching: we first studied the BF algorithm, given that we often need to backtrack, always do some work hard, in order to improve the time and space of the algorithm, introduced the next array (as to why the increase in time, as mentioned below), that is, using the next array, we do not need to go back, Can be directly compared, this is the KMP algorithm
So say: from BF to KMP, just simple abandon BF algorithm, spend time space too long too big, all in progress ...
Pattern matching or string matching of strings:
The location of a substring is the first occurrence of a substring in the main string from a POS character.
In general, the main string s is called the target string, and the substring T is called the pattern string
BF algorithm:
Brute-force, also known as Brute Force (violence) matching algorithm
1, starting from the POS character of the main string s, and comparing the first character of the pattern string T,
2, if equal, the subsequent characters are compared one by one; otherwise, go back to the pos+1 character of the main string, continue to compare with the first character of the pattern string T, repeat step 2, know that each word in the pattern string T nonalphanumeric and the main string is equal (return the first character on the current main string s match) or find the main string s All characters after the POS position (return 0)),
Program 1:
[CPP] View plain copy #include <stdio.h> #include <string.h> #include <malloc.h> int bfmode (char *s, char *t, int pos) { int flag1,flag; int i,j; int slength, tlength; slength = strlen (s); tlength = strlen ( T); for (i = pos; i < slength; i++) { flag1 = i, flag = 0; for (j = 0; j < tlength; j++) { if (s[i] == t[j] && i < slength) { flag ++; i++; } else break; } if (flag == tlength) { return Flag + 1; } i = flag1; } return 0; } int Main () { char s[50]; //Target string char t[20]; // The pattern string is also a substring int pos; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%s", s); &NBSP;SCANF ("%s", t); &n