基于优化的KMP算法的王卓数据结构算法基础第四章病毒感染检测案例代码实现

//输入char[]请输入格式如"3abc"的格式
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define TRUE    1
#define FALSE   0
#define OK      1
#define ERROR   0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAXSIZE 100
#define SElemType int
typedef struct chunk {
    char ch[MAXSIZE];
    struct chunk * next;
} chunk,*linkchunk;
typedef struct {
    linkchunk head,tail;
    int curlen;
} LString;
void cre_LS(LString &L);
void output(LString L);
void cre_nextval(char T[],int nextval[]);
bool KMP(char T[],char S[],int sj,int tj);
void cmpsingle(char T[],char S[]);
void virustest(LString vs,LString man);
int main() {
    LString vs,man;
    cre_LS(vs);
    cre_LS(man);
    virustest(vs,man);
    return 0;
}
void virustest(LString vs,LString man) {
    linkchunk p,q;
    p=vs.head->next;
    q=man.head->next;
    while(q&&p) {
        printf("%s",p->ch);
        printf("    ");
        printf("%s      ",q->ch);
        cmpsingle(p->ch,q->ch);
        q=q->next;
        p=p->next;
    }
}
void cmpsingle(char T[],char S[]) {
    char *p=T;
    int tj=strlen(T)-1;
    char tem[256];
    int i=0;
    int count=2;
    while (count<=strlen(T)) {
        *(tem+i)=*(++p);
        ++i;
        count++;
    }
    strcat(T,tem);
    bool s=false;
    i=0;
    while(i<tj) {
        s=KMP(T+i,S,strlen(S)-1,tj);
        i++;
        if(s) break;
    }
    if(s) printf("YES\n");
    else printf("NO\n");
}
bool KMP(char T[],char S[],int sj,int tj) {
    int i=1;
    int j=1;
    int nextval[255];
    cre_nextval(T,nextval);
    while(i<=sj&&j<=tj) {
        if(j==0||T[j]==S[i]) {
            i++;
            j++;
        } else {
            j=nextval[j];
        }
    }
    if( j>tj)return true;
    else return false;
}
void cre_nextval(char T[],int  nextval[]) {
    int j=1;
    int k=0;
    nextval[0]=0;
    nextval[1]=0;
    int num=T[0]-'0';
    while(j<num) {
        if(k==0||T[j]==T[k]) {
            ++j;
            ++k;
            if(T[j]==T[k]) {
                nextval[j]=nextval[k];
            } else {
                nextval[j]=k;
            }
        } else {
            k=nextval[k];
        }
    }
}
void cre_LS(LString &L) {
    L.head=new chunk;
    L.head->next=NULL;
    linkchunk r=L.head;
    linkchunk p=NULL;
    int n=1;
    while(n<11) {
        p=new chunk;
        p->next=NULL;
        printf("请输入字符串");
        gets(p->ch);
        r->next=p;
        r=p;
        n++;
    }
    printf("输入结束\n");
    L.tail=r;
    L.curlen=n-1;
}
void output(LString L) {
    linkchunk p=L.head->next;
    while(p) {
        printf("\n");
        puts(p->ch);
        p=p->next;
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值