https://leetcode.com/problems/implement-strstr/ 28. Implement strStr()
Violence algorithm:
int ViolentMatch ( char * S, char * P) { int sLen = strlen (S); int pLen = strlen (P); int I = 0 ; int J = 0 ; the while (I <sLen && J < pLen) { IF (S [I] == P [J]) { // ① successful if the character matches the current (i.e., S [i] == P [j ]), then ++ I, J ++ I ++ ; J ++ ; } the else { //② If the mismatch (! I.e., S [i] = P [j ]), so that I = I - (J -. 1), J 0 = I = I - J + . 1 ; J = 0 ; } } // successful match , p return position in the pattern string s in the text string, otherwise -1 IF (J == pLen) return I - J; the else return - . 1 ; }
KMP (Knuth-Morris-Pratt) algorithm:
When T [i]! = P [j] when
There T [ij ~ i-1] == P [0 ~ j-1]
The P [0 ~ k-1] == P [jk ~ j-1]
必然:T[i-k ~ i-1] == P[0 ~ k-1] -->because k<j
If the given pattern string is: "ABCDABD", from left to right through the entire pattern strings, each substring which prefixes and suffixes table are as follows:
That is the maximum length table, the original substring pattern string corresponding to each of the common prefixes and suffixes of elements (hereinafter referred to as "Maximum length"):
KMP algorithm: = NEXT array subscript more readily appreciated from 0 =
class Solution { public: void GenNext(string p, int next[]){ int plen = p.size(); next[0] = 0; int j = 0; for(int i=1; i<plen; ){ if(p[j] == p[i]){ next[i] = j+1; j++; i++; } else{ if(j!=0) j = next[j-1]; else{ next[i] = 0; i++; } } } } int strStr(string haystack, string needle) { int slen = haystack.size(); int plen = needle.size(); if(slen < plen) return -1; if(needle == "" ||haystack == "") return 0; int i=0, j=0; int next[plen]; GenNext(needle, next); while(i<slen && j<plen){ if(haystack[i]==needle[j]){ i++; j++; }else{ if(j!=0) j = next[j-1]; else i++; } } if(j==plen) return i-j; return -1; } };
KMP algorithm Reference: https://www.cnblogs.com/ZuoAndFutureGirl/p/9028287.html
More advanced search algorithms:
BM algorithm Sunday algorithm https://www.cnblogs.com/ZuoAndFutureGirl/p/9028287.html