Judge whether a string is a substring of another string, that is, the implementation of the strstr () function. A simple implementation method is the BF algorithm.
1. BF algorithm
int BF(char *s, char *p){ if(s==NULL || p==NULL)return -1; int i=0; int j; while(i<strlen(s)){ j=0; while(s[i]==p[j] && j<strlen(p)){ i++; j++; } if(j==strlen(p))return i-j; i=i-j+1; } return -1;}
2. KMP Algorithm
The principles of the KMP algorithm are explained in many articles, so I won't talk about it (I don't quite understand it ......). The key aspect of the entire KMP algorithm is the implementation of the next array.
KMP algorithm subject:
int KMP(char *s, char *p){ if(s==NULL || p==NULL)return -1; int next[100]; get_next(next, p); int i=0; int j=0; while(i<strlen(s)){ if(j==-1 || s[i]==p[j]){ i++; j++; }else{ j=next[j]; } if(j==strlen(p))return i-j; } return -1;}
Implementation of the get_next function:
void get_next(int *next, char *p){ if(next==NULL || p=NULL)return; int i=0; int j=-1; next[0]=-1; while(i<strlen(p)-1){ if(j==-1 || p[i]==p[j]){ i++; j++; next[i]=j; }elseP{ j=next[j]; } }}
Note that the implementation of the get_next function is only related to the sub-string...
Determine whether a string contains another string (KMP, BF)