Determine whether a string contains another string (KMP, BF)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.