//Markdown编辑器我没法从IDE复制代码了
//就很生气
#ifndef PCH_H
#define PCH_H
#include<cstdlib>
#include<stdio.h>
#include<malloc.h>
#include<math.h>
#include<iostream>
typedef int Status;
constexpr auto OK = 1;
constexpr auto ERROR = 0;
constexpr auto MAXSIZE = 20;
constexpr auto TSIZE = 5;
typedef struct
{
char ch[MAXSIZE + 1];
int length;//串当前长度
}SString;
int index_KMP(SString S, SString T, int pos, int next[]);
//模式串的next函数值取决于模式串本身
void get_next(SString T,int next[]);
//计算next函数的修正值
void get_nextval(SString T, int nextval[]);
//求模式串T的next值并存入数组next
//----------复习串的基本函数-------------
Status StrAssign(SString &T,char ch[]);//初始化T为有值串
Status StrPrint(SString T);//打印串(废话
#endif
----------------------------------------------------------------------------------
#include "pch.h"
int index_KMP(SString S, SString T, int pos,int nextval[])
{
int i, j;
i = pos;
j = 1;//不清晰写法
while(i<=S.length&&j<=T.length)
{
if (j==0||S.ch[i-1]==T.ch[j-1])
{
++i;
++j;
}
else
j = nextval[j];
}
if (j>T.length)
return i - T.length;
return ERROR;//匹配失败!
}
void get_next(SString T, int next[])
{
int i = 1;
int j = 0;
next[1] = 0;//第一个不匹配,需要i,j都+1
while (i<T.length)//自己是主串也是模式串
{
if (j==0||T.ch[i-1]==T.ch[j-1])
{
++i;
++j;
next[i] = j;
}
else
{
j = next[j];
}
}
}
void get_nextval(SString T, int nextval[])
{//求next函数修正值 存入函数nextval[]
int i = 1;
int j = 0;
nextval[1] = 0;
while (i < T.length)
{
if (j == 0 || T.ch[i - 1] == T.ch[j - 1])
{
++i;
++j;
if (T.ch[i-1] != T.ch[j-1])
nextval[i] = j;
else nextval[i] = nextval[j];
//似懂非懂
}
else
j = nextval[j];
}
}
//设计算法的老师们真的是神仙
//几句话给我搞得七荤八素找不着北
Status StrAssign(SString& T, char ch[])
{//初始化
if (!ch)return ERROR;//数组空
int j = strlen(ch);
int i = 0;
for (; i < j; i++)
{
T.ch[i] = ch[i];
}
T.ch[i] = '\0';
T.length = j;
return OK;
}
Status StrPrint(SString T)
{
if (T.length == 0) return ERROR;
for (int i=0;i<T.length;i++)
{
std::cout << T.ch[i]<<" ";
}
return OK;
}
-----------------------------------------------------------------------------
// ConsoleApplication15.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include <stdio.h>
int main()
{
SString A,B;
char ch[TSIZE] = "abaa";//模式串,最后一位自动补上'\0'
char ch2[MAXSIZE+1]="acabaabaabcacaabc";//主串
StrAssign(A, ch2);//初始化主串A
StrAssign(B, ch);//初始化模式串B
std::cout << "主串:";
StrPrint(A);
std::cout << "\n"<<"模式串:";
StrPrint(B);
int next[TSIZE+1];
get_next(B, next);
for (int i=1;i<=B.length;i++)
{
std::cout << next[i];
}
std::cout<<"匹配中。。。位置:"<<index_KMP(A, B, 1, next);
}