鱼C论坛

 找回密码
 立即注册
查看: 3056|回复: 3

KMP优化算法求出的next数组错误

[复制链接]
发表于 2013-9-8 15:57:17 | 显示全部楼层 |阅读模式
1鱼币
  1. //预定义常量和类型

  2. //函数结果状态代码
  3. #include <stdio.h>
  4. #include<stdlib.h>
  5. #include <time.h>
  6. #include<windows.h>
  7. #include<math.h>
  8. //#include<unistd.h>
  9. #define TRUE 1
  10. #define FALSE 0
  11. #define OK 1
  12. #define ERROR 0
  13. #define INFEASIBLE -1
  14. #define OVERFLOW -2
  15. typedef int Status;
  16. #define MAX_STR_LEN 255

  17. typedef unsigned char String[MAX_STR_LEN+1];

  18. Status StrAssign(String T,char *chars)
  19. {
  20. //生成一个其值等于chars的串T
  21. int i;
  22. if(strlen(chars)>MAX_STR_LEN)
  23. {
  24. return ERROR;
  25. }
  26. else
  27. {
  28. T[0]=strlen(chars);//0号单元存放串的长度
  29. for(i=1;i<=T[0];i++)//从1号单元起复制串的内容
  30. {
  31. T[i]=*(chars+i-1);
  32. }
  33. return OK;
  34. }

  35. }

  36. void get_next( String T, int *next )
  37. {
  38. int j = 0;
  39. int i = 1;
  40. next[1] = 0;

  41. while( i < T[0] )
  42. {
  43. if( 0 == j || T[i] == T[j] )
  44. {
  45. i++;
  46. j++;
  47. if( T[i] != T[j] )
  48. {
  49. next[i] = j;
  50. }
  51. else
  52. {
  53. next[i] = next[j];
  54. }
  55. }
  56. else
  57. {
  58. j = next[j];
  59. }
  60. }

  61. for(i=1;i<=T[0];i++)
  62. {
  63. printf("%d ",next[i]);
  64. }
  65. printf("\n");
  66. }

  67. // 杩斿洖瀛愪覆T鍦ㄤ富涓睸绗琾os涓瓧绗︿箣鍚庣殑浣嶇疆
  68. // 鑻ヤ笉瀛樺湪锛屽垯杩斿洖0
  69. int Index_KMP( String S, String T, int pos )
  70. {
  71. int i = pos;
  72. int j = 1;
  73. int next[255];

  74. get_next( T, next );

  75. while( i <= S[0] && j <= T[0] )
  76. {
  77. if( 0 == j || S[i] == T[j] )
  78. {
  79. i++;
  80. j++;
  81. }
  82. else
  83. {
  84. j = next[j];
  85. }
  86. }

  87. if( j > T[0] )
  88. {
  89. return i - T[0];
  90. }
  91. else
  92. {
  93. return 0;
  94. }
  95. }

  96. main()
  97. {
  98. char *chars1="ababaaaba"; //这里赋值给T
  99. char *chars2="fababcabdabababaaabacabeabababe";
  100. String T,S;
  101. int next[255];

  102. StrAssign(T,chars1);
  103. StrAssign(S,chars2);

  104. get_next(T, next );

  105. return 0;
  106. }
复制代码

模式串T="ababaaaba"
优化算法得出的next数组=0 1 0 1 0 4 2 1 0
正确的next数组应该    是=0 1 1 2 3 4 2 2 3

请问是为什么,是算法错了吗

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2013-9-8 20:34:26 | 显示全部楼层
谁帮我看下啊
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2013-9-9 17:13:30 | 显示全部楼层
谁帮下我啊
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2013-9-9 18:28:29 | 显示全部楼层
没有问题了,两个数组都可以得到一样的匹配结果,昨天支行时老出错,今天就可以了,谢谢大家,问题解决了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-16 15:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表