采用 KMP 算法编程实现病毒感染检测算法

采用 KMP 算法编程实现病毒感染检测算法

#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;

typedef struct {
	char ch[600]; //若是非空串,则按串长分配存储区,否则 ch 为 NULL
	int len; //串长度
}HString;


int Index_BF(HString S, HString T, int pos)
{//返回模式 T 在主串 S 中第 pos 个字符开始第一次出现的位置。若不存在,则返回值为 0
		//其中,T 非空,1≤pos≤StrLength(S)
	int i, j;
	i = pos; j = 1;
	while (i <= S.len &&j <= T.len)
	{
		if (S.ch[i] == T.ch[j]) { ++i; ++j; } //继续比较后继字符
		else { i = i - j + 2; j = 1; } //指针后退重新开始匹配
	}
	if (j > T.len) 
		return i - T.len;
	else return 0;
}

void Virus_detection()
{
	int num, m, flag, i, j;
	char Vir[600];
	HString Virus, Person, temp;
	ifstream inFile("病毒感染检测输入数据.txt");
	ofstream outFile("病毒感染检测输出结果.txt");
	inFile >> num;//读取待检测的任务数
	while (num--) //依次检测每对病毒 DNA 和人的 DNA 是否匹配
	{
		inFile >> Virus.ch + 1;//读取病毒 DNA 序列
		inFile >> Person.ch + 1;//读取人的 DNA 序列
		strcpy_s(Vir, Virus.ch);
		Virus.len = strlen(Virus.ch) - 1;
		Person.len = strlen(Person.ch) - 1;
		flag = 0;//用来标识是否匹配,初始为 0,匹配后为非
		m = Virus.len;
		for (i = m + 1, j = 1; j <= m; j++)
			Virus.ch[i++] = Virus.ch[j];
		Virus.ch[2 * m + 1] = '\0';
		for (i = 0; i < m; i++) {
			for (j = 1; j <= m; j++)
				temp.ch[j] = Virus.ch[i + j];
			temp.ch[m + 1] = '\0';
			temp.len = m;
			Index_BF(Person, temp, 1);
			flag = Index_BF(Person, temp, 1);
			if (flag)
				break;
		}
		if (flag)
			outFile << Vir + 1 << "	" << Person.ch + 1 << " " << "	YES" << endl;
		else
			outFile << Vir + 1 << "	" << Person.ch + 1 << " " << "	NO" << endl;
	}
}

int main()
{
	Virus_detection();
	return 0;
}

病毒感染检测输入数据.txt(文件放在.exe文件同一文件夹内,此文件需要自己建立)
10
baa bbaabbba
bba aaabbbba
aabb abceaabb
aabb abaabcea
abcd cdabbbab
abcd cabbbbab
abcde bcdedbda
acc bdedbcda
cde cdcdcdec
cced cdccdcce

输出结果(输出文件为自动生成)
在这里插入图片描述

  • 4
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值