#include<stdio.h>
#include<string.h>
#define ERROR 0
#define OK 1
#define MAXSIZE 255
typedef int Status;
//串的顺序存储
typedef struct
{
char ch[MAXSIZE + 1];//下标为0的分量闲置不用
int length;//串的当前长度
}SString;
//串的堆式顺序存储结构
typedef struct
{
char *ch; //若是非空串,则按串长分配存储区,否则ch为NULL,为新产生的串动态分配存储空间
int length;
}HString;
//串的链式存储结构
#define CHUNKSIZE 80
typedef struct Chunk
{
char ch[CHUNKSIZE];
struct Chunk *next;
}Chunk;
typedef struct
{
Chunk *head, *tail;
int length;
}LString;
//BF算法
//查找起始位置pos,主串S,模式串T
int Index_BF(SString T,SString S, int pos)
{
int i, j;
i = pos; j = 1;
while (i <= S.length&&j <= T.length)
{
if (S.ch[i] == T.ch[j]) { ++i; ++j; }//相等,继续比较
else { i = i - j + 2; j = 1; }//后退,重新开始比较
}
if (j > T.length)return i - T.length;
else return 0;
}
/*
int main()
{
SString T; SString S; int pos,x;
scanf_s("%d %s",&T.length, T.ch,10); scanf_s("%d %s",&S.length, S.ch,10);
x=Index_BF(T, S, 1);
printf("%d", x);
}
*/
//KMP
void get_next(SString T, int next[100])
{
int i, j;
i = 1; next[1] = 0; j = 0;
while (i < T.length)
{
if (j == 0 || T.ch[i] == T.ch[j]) { ++i; ++j; next[i] = j; }
else j = next[j];
}
}
int Index_KMP(SString S, SString T, int pos,int next[])
{
int i, j;
i = pos; j = 1;
while (i <= S.length&&j <= T.length)
{
if (j == 0 || S.ch[i] == T.ch[j]) { ++i; ++j; }
else j = next[j];
}
if (j > T.length)return i - T.length;
else return 0;
}
void get_nextval(SString T, int nextval[])
{
int i, j;
i = 1; nextval[1] = 0; j = 0;
while (i < T.length)
{
if (j == 0 || T.ch[i] == T.ch[j])
{
++i; ++j;
if (T.ch[i] != T.ch[j])nextval[i] = j;
else nextval[i] = nextval[j];
}
else j = nextval[j];
}
}
int main()
{
SString T; SString S; int pos, x,next[100];
scanf_s("%s", T.ch, 10); scanf_s("%s",S.ch, 10);
S.length = strlen(S.ch)-1; T.length = strlen(T.ch)-1;
get_next(T, next);
printf("%d,%d", S.length, T.length);
x = Index_BF(T, S, 1);
printf("\n%d", x);
x = Index_KMP(S, T, 1,next);
printf("\n%d\n", x);
}
//矩阵压缩
Status n_to_ij(int n, int &i, int &j)
{
int sum =0,num = 0;
int k;
for (;sum < n + 1; k++)
{
sum = sum + k;
num++;
}
i = k - 1;
j = n - (sum - num) + 1;
}
串的多种存储结构
于 2023-12-03 05:16:18 首次发布