KMP算法C语言实现。弄了好久才搞好。。。
我的这个算法中数组的第一位没有像教材中那样用来存数组的大小,所以会有些许的不同。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | // KMP算法 #include <stdio.h> #include <stdlib.h> #include <string.h> void get_next( char *T, int next[]) //修正前的next数组 { int i = 1,j = 0; next[0] = -1; next[1] = 0; int m = strlen (T); while (i< strlen (T)-1) { if (j == -1||T[j]==T[i]) { ++i; ++j; next[i] = j; } else j = next[j]; } } void get_nextval( char *T, int nextval[]) //修正后的nextval数组 { int i = 1,j = 0; nextval[0] = -1; nextval[1] = 0; int m = strlen (T); while (i< strlen (T)-1) { if (j == -1||T[j]==T[i]) { ++i; ++j; if (T[i]!=T[j]) nextval[i] = j; else nextval[i] = nextval[j]; } else j = nextval[j]; } } int Index_kmp( char *S, char *T, int pos, int next[]) //逐项比较 { int j = 0,i = pos,lens= strlen (S),lent= strlen (T); get_next(T,next); while (i<lens&&j<lent) { if (S[i]==T[j]||j==-1) { i++;j++; } else j = next[j]; } if (j>=lent) return i-lent; else return -1; } int main() { char *S= "adbadabbaabadabbadada" ,*T= "adabbadada" ; int m; int *next = ( int *) malloc (( strlen (T)+1)* sizeof ( int )); //修正前的next数组 int *nextval = ( int *) malloc (( strlen (T)+1)* sizeof ( int )); //修正后的nextval数组 get_next(T,next); printf ( "修正前next数组为:" ); for (m = 0;m< strlen (T);m++) { printf ( "%d " ,next[m]+1); } get_nextval(T,nextval); printf ( "\n修正后的nextval数组为:" ); for (m=0;m< strlen (T);m++) { printf ( "%d " ,nextval[m]+1); } int t = Index_kmp(S,T,0,nextval); if (t==-1) printf ( "\n无匹配项!\n" ); else { printf ( "\n在第%d项开始匹配成功\n" ,t+1); } return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步