brute force BF算法 暴力算法
#include <stdio.h>#include <string.h>
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 == target)
{
++i; // it seems there is not difference between ++i and i++
++j;
}
else
{
i = i - j + 1;
j = 0;
}
}
if(j==strlen(target))
return (i-strlen(target));
else
return -1;
}
页:
[1]