字符串模式匹配之Brute-Force算法

2920阅读 0评论2013-09-04 ygfinsight
分类:C/C++

Brute-Force 算法思想:
        Brute-Force算法是一种字符串模式匹配算法
        思想是从主串的第一个字符开始,与子串的第一
        个字符比较,若相同则继续比较,若不相同,则
        从主串的第二个字符开始与子串的第一个字符继续比较
        如此不断比较,若存在字串中的每个字符依次和主串中
        的一个连续字符序列相等,则匹配成功,返回字串第一个字符
        在主串中的位置
实现:

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <string.h>
  3. #define MAXSIZE 100

  4. int BF_index(char* s,int start,char* t)
  5. {
  6.     int i=start,j=0,r;
  7.     while(i<strlen(s) && j<strlen(t)){
  8.         if(s[i]==t[j]){
  9.             i++;
  10.             j++;
  11.         }
  12.         else{
  13.             i=i-j+1;
  14.             j=0;
  15.         }
  16.     }
  17.     //判断查找是否成功
  18.     if(j==strlen(t)) return r=i-strlen(t);
  19.     else
  20.         r=-1;
  21.     return r;
  22. }
  23. int main()
  24. {
  25.     char *str1="cddcdc";
  26.     char *str2="cdc";
  27.     printf("从主串中的第%d个字符开使是匹配的。\n",BF_index(str1,0,str2));
  28.     return 0;
  29. }

上一篇:ubuntu 下安装 pthread man
下一篇:【我解C语言面试题系列】012 查找整数数组中第二大的数