brute force 暴力算法

#include
#include


int main()
{
    int BF_index(char source[], char target[]);


    char source[]="abcd";
    char target[]="cd";
    int pos; //position


    pos = BF_index( source, target);
    if (-1==pos)
        printf("not found!");
    else
        printf("the target is positioned at %d\n",pos);
    return 0;
}




int BF_index(char source[], char target[])      //brute force
{
    if (strlen(source) < 1 || strlen(target)<1)
        return -1;


    int i = 0, j = 0;
    while (i < strlen(source) && j < strlen(target))
    {
        if (source[i] == target[j])
        {
            ++i;    //it seems there is no difference between ++i and i++
            ++j;
        }
        else
        {
            i = i - j + 1;
            j = 0;
        }
    }


    if(j==strlen(target))
        return (i-strlen(target));
    else
        return -1;
}

你可能感兴趣的:(brute force 暴力算法)