[Data structures]String
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 255
typedef unsigned char SString[MAX+1];
int next[MAX];
/*
* 0 :j == 1
* k :T[1...k-1] == T[j-(k-1)...j-1]
* 1 :Others
* */
void get_next(SString T, int next[])
{
int i,j;
i = 1;
next[1] = 0;
j = 0;
while(i < T[0]){
if(j == 0 || T[i] == T[j]){
i++;
j++;
#if 1
next[i] = j;
#else
if(T[i] != T[j]){
next[i] = j;
}else{
next[i] = next[j];
}
#endif
}else{
j = next[j];
}
}
}
int Index_kmp(SString S, SString T, int pos)
{
int i,j;
i = pos;
j = 1;
while(i<=S[0] && j<=T[0]){
if(j == 0 || S[i] == T[j]){
i++;
j++;
}else{
j = next[j];
}
}
if(j>T[0]){
return i-T[0];
}else{
return 0;
}
}
void main()
{
char *original_t = "abaabc";
char *original_s = "aaaaabaabcbbbb";
SString T,S;
int i;
printf("log.anycle.com\n\n");
printf("Original data:\n");
printf("S:%s\n", original_s);
printf("T:%s\n", original_t);
memcpy(T+1, original_t, strlen(original_t));
memcpy(S+1, original_s, strlen(original_s));
T[0] = strlen(original_t);
S[0] = strlen(original_s);
printf("Get next of T:\n");
get_next(T, next);
for(i=1; i<=T[0]; i++){
printf(" %d", next[i]);
}
printf("\n");
printf("Get position of T in S:\n");
printf(" %d\n", Index_kmp(S, T, 0));
}
日历
最新微语
- 有的时候,会站在分叉路口,不知道向左还是右
2023-12-26 15:34
- 繁花乱开,鸟雀逐风。心自宁静,纷扰不闻。
2023-03-14 09:56
- 对于不可控的事,我们保持乐观,对于可控的事情,我们保持谨慎。
2023-02-09 11:03
- 小时候,
暑假意味着无忧无虑地玩很长一段时间,
节假意味着好吃好喝还有很多长期不见的小朋友来玩...
长大后,
这是女儿第一个暑假,
一个半月...
2022-07-11 08:54
- Watching the autumn leaves falling as you grow older together
2018-10-25 09:45
分类
最新评论
- Goonog
i get it now :) - 萧
@Fluzak:The web host... - Fluzak
Nice blog here! Also... - Albertarive
In my opinion you co... - ChesterHep
What does it plan? - ChesterHep
No, opposite. - mojoheadz
Everything is OK!... - Josephmaigh
I just want to say t... - ChesterHep
What good topic - AnthonyBub
Certainly, never it ...
发表评论: