Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12952
  • 博文数量: 16
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 170
  • 用 户 组: 普通用户
  • 注册时间: 2013-05-08 11:44
文章分类
文章存档

2014年(16)

我的朋友
最近访客
kmp

分类: C/C++

2014-04-29 15:35:42


点击(此处)折叠或打开

  1. void getnext(char a[], int next[], int n)
  2. {
  3.         int i, j;

  4.         i = 1;
  5.         j = 0;
  6.         next[0] = -1;
  7.         while (i < n) {
  8.                 if (-1 == j || a[i] == a[j]) {
  9.                         i++;
  10.                         j++;
  11.                         if (a[i] != a[j])
  12.                                 next[i] = j;
  13.                         else
  14.                                 next[i] = next[j];
  15.                 } else
  16.                         j = next[j];

  17.         }
  18. }

  19. int substr(char str[], char a[])
  20. {
  21.         int i, j;
  22.         int n;
  23.         int *next;

  24.         n = strlen(a);
  25.         next = malloc(n * sizeof(int));
  26.         getnext(a, next, n);
  27.         i = 0; j = 0;

  28.         while (str[i] != '\0' && j < n) { // 到str末尾 或者匹配成功
  29.                 if (j == -1 || str[i] == a[j]) {
  30.                         i ++;
  31.                         j ++;
  32.                 } else
  33.                         j = next[j];
  34.         }

  35.         free(next);
  36.         if (j == n)
  37.                 return i - n;
  38.         else
  39.                 return -1;
  40. }
另一种getnext的方法

点击(此处)折叠或打开

  1. void getnext(char a[], int next[], int n)
  2. {
  3.         next[0] = -1;
  4.         for (int i=1; i<n; i++) {
  5.                 next[i] = 0;
  6.         }

  7.         for (int i=1; i<n; i++) {
  8.                 if (a[i] == a[0]) {
  9.                         next[i] = next[i]==0 ? -1 : next[i];
  10.                         int k = 1;
  11.                         int h = i+1;
  12.                         while (h<n && a[k]==a[h]) {
  13.                                 h++;
  14.                                 k++;
  15.                         }
  16.                         if (h < n) {
  17.                                 next[h] = k;
  18.                         }
  19.                 }
  20.         }
  21. }


阅读(130) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:c语言困惑

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