暴力匹配(Brute-Force-Match)是字符串匹配算法里最基础的算法,虽然效率比较低,但胜在方便理解,在小规模数据或对时间无严格要求的状况下能够考虑。算法
#include <stdio.h> #include <string.h> int bf(char *l,char *s); int main(void) { char s1[201],s2[201]; //根据须要设定数组大小 printf("母串:"); scanf("%s",s1); printf("子串:"); scanf("%s",s2); int a=strlen(s1),b=strlen(s2),re=0; if(a>=b) //母串长度要比子串长 { re=bf(s1,s2); if(re==1) printf("%s是%s的子串",s2,s1); return 0; } else printf("没法匹配"); return 0; } int bf(char *l,char *s) { if(!strcmp(l,s)) //若是两个字符串相同直接返回 return 1; int ll=strlen(l),sl=strlen(s),di=ll-sl; for(int i=0;i<=di;i++) { int temp=0; for(int j=0;j<sl;j++) { if(l[i+j]==s[j]) continue; else { temp=1; break; } } if(temp==1) continue; else if(temp==0) return 1; } printf("子串不存在"); return 0; }
每次从子串与母串的第一个字符开始比较,如果匹配成功则继续下一个字符的匹配;如果匹配失败则从母串的下一个字符开始与子串的第一个字符从新匹配,循环往复直到匹配成功或者匹配失败。数组
咱们设子串长为m,母串长为n,同时m比n小的多。code
在最好状况下,子串与母串的失配都是发生在第一个字符处,时间复杂度为O(m+n)。
在最坏的状况下,即子串每一次与母串失配都是在最后一个字母时,时间复杂度为O((m*n)。字符串