Brute-Force算法的基本思想是:
1) 从目标串s 的第一个字符起和模式串t的第一个字符进行比较,若相等,则继续逐个比较后续字符,否则从串s 的第二个字符起再重新和串t进行比较。
2) 依此类推,直至串t 中的每个字符依次和串s的一个连续的字符序列相等,则称模式匹配成功,此时串t的第一个字符在串s 中的位置就是t 在s中的位置,否则模式匹配不成功。
该算法最坏情况下要进行M*(N-M+1)次比较,时间复杂度为O(M*N)。
算法流程图:
代码:
#include <iostream>
using namespace std;
#define MAXSIZE 255
typedef struct
{
int length;
char *ch;
}HString;
int index_BF(HString s,HString t,int pos)
{
int i=pos,j=0;
while(i<s.length&&j<t.length)
{
if(s.ch[i]==t.ch[j]){++i;++j;}
else
{
i=i-j+1;
j=0;
}
}
if(j>=t.length)return i-t.length;
else return -1;
}
void strAssign(HString &s,char *c)
{
s.ch=new char[MAXSIZE];
strcpy(s.ch,c);
s.length=strlen(c);
}
int main()
{
int x;
HString s,t;
strAssign(s,"dasdsadsa");
strAssign(t,"ad");
x=index_BF(s,t,0);
cout<<x<<endl;
return 0;
}