数据结构字符串匹配——Brute-Force算法

1513阅读 2评论2011-08-16 sunjiangang-ok
分类:C/C++

在数据结构的书上有这个问题的描述。

问题描述:已知一字符串str,并给出字串sub_str,然后判断sub_str是不是在str中,并且输出相应的信息。

算法描述:使用三个指示器——i, j, start。

start:表示每趟比较的时候str的起点。

i:表示在每趟比较当中,str的移动指针。

j:表示在每趟比较当中,sub_str的移动指针。

  1. #include <stdio.h>
  2. #include <string.h>

  3. #define M 20

  4. int main()
  5. {
  6.     char str[M], sub_str[M];
  7.     int i, j, start;

  8.     fprintf(stdout, "Input string:\n");
  9.     fscanf(stdin, "%s", str);
  10.     fprintf(stdout, "Input sub string:\n");
  11.     fscanf(stdin, "%s", sub_str);
  12.     
  13.     start = 0;
  14.     i = start;
  15.     j = 0;
  16.     while(i < strlen(str) && j < strlen(sub_str)) {
  17.         if(str[i] == sub_str[j]) {
  18.             i++;
  19.             j++;
  20.         } else {
  21.             start++;
  22.             i = start;
  23.             j = 0;
  24.         }
  25.     }
  26.     
  27.     if(j == strlen(sub_str)) {
  28.         printf("match successfully~\n");
  29.     } else {
  30.         printf("match unsuccessfully~\n");
  31.     }

  32.     return 0;
  33. }

测试结果:

  1. ^_^[sunny@sunny-laptop ~/DS]102$ ./a.out
  2. Input string:
  3. abcdefg
  4. Input sub string:
  5. abc
  6. match successfully~
  7. ^_^[sunny@sunny-laptop ~/DS]103$ ./a.out
  8. Input string:
  9. abcdefg
  10. Input sub string:
  11. hi[]
  12. match unsuccessfully~

上一篇:linux内核list.h头文件分析(六)——hlist分析
下一篇:巧记const, char, *的区别

文章评论