Chinaunix首页 | 论坛 | 博客
  • 博客访问: 39466
  • 博文数量: 6
  • 博客积分: 98
  • 博客等级: 民兵
  • 技术积分: 60
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-13 16:02
文章分类

全部博文(6)

文章存档

2011年(6)

分类: C/C++

2011-04-18 01:40:44

数据结构书上的SString是默认下标0存字符串长度的,改了以下:
如果有错,欢迎指正:


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

  4. int get_nextval(char *pattern, int next[])
  5. {
  6.     //get the next value of the pattern
  7.     int i = 0, j = -1;
  8.     next[0] = -1;
  9.     int patlen = strlen(pattern);
  10.     while ( i < patlen - 1){
  11.         if ( j == -1 || pattern[i] == pattern[j]){
  12.             ++i;
  13.             ++j;
  14.             if (pattern[i] != pattern[j])
  15.                 next[i] = j;
  16.             else
  17.                 next[i] = next[j];
  18.         }
  19.         else
  20.             j = next[j];
  21.         }

  22.     return(0);
  23. }

  24. int kmpindex(char *target, char *pattern, int pos)
  25. {
  26.     int tari = pos, pati = 0;
  27.     int tarlen = strlen(target), patlen = strlen(pattern);
  28.     int *next = (int *)malloc(patlen * sizeof(int));
  29.     get_nextval(pattern, next);
  30.     while ( tari < tarlen && pati < patlen ){
  31.         if (pati == -1 ||target[tari] == pattern[pati]){
  32.             ++tari;
  33.             ++pati;
  34.             }else{
  35.                 pati = next[pati];
  36.             }
  37.     }    
  38. if(next != NULL) free(next);
  39. next = NULL;
  40. if (pati == patlen)
  41.     return tari - pati;
  42. else
  43.     return -1;
  44. }


  45. int main()
  46. {
  47.     char target[50], pattern[50];
  48.     printf("imput the target:\n" );
  49.     scanf("%s",target);
  50.     printf("imput the pattern:\n" );
  51.     scanf("%s",pattern);
  52.     int ans = kmpindex(target,pattern,0);
  53.     if (ans == -1)
  54.         printf("error\n");
  55.     else
  56.         printf("index:%d\n",ans);
  57.     return 0;
  58. }
阅读(4367) | 评论(0) | 转发(0) |
0

上一篇:+U

下一篇:买了几本盗版书~~~

给主人留下些什么吧!~~