Given two strings S, P, S contained in how to determine P? (Assuming a longer string S, P is required to be consecutive characters in S)
This is the classic string matching problem. Violence match omitted to say, a better solution is to KMP. For a novice, want to learn KMP, it is recommended to see the following two articles:
KMP string matching algorithm (Ruan Yifeng)
From start to finish a thorough understanding of KMP (2014 Nian the August 22)
If you explain in next The second array is not very good, I suggest reading this
[Classic] algorithm --KMP, in-depth explanation to solve the next array
This paper gives the realization of kmp:
int getnext(char *p, int next[]) { int len = strlen(p); next[0] = -1; int k = -1, j = 0; while (j < len) { while (k >= 0 && p[j] != p[k]) { k = next[k]; } k++; j++; next[j] = k; } return 0; } void kmp(char *s, char *p) { int slen = strlen(s); int plen = strlen(p); int *next = new int[plen + 1]; // size is plen + 1 getnext(p, next); int i = 0, j = 0; while (i < slen) { while (j >= 0 && s[i] != p[j]) { j = next[j]; } i++; j++; if (j == plen) { printf("found substring at index: %d\n", i - j); j = next[j]; // to find more matches } } delete [] next; // do not forget }
analysis:
If the text string of length n, the pattern string length is m, then the time matching process complexity is O (n), calculate next count of O (m) time, KMP overall time complexity is O (m + n).
Reference:
algorithm to find substring in a string (KMP Algorithm)
Reproduced in: https: //www.cnblogs.com/gattaca/p/4723530.html