假设病毒的DNA序列为baa,患者1的DNA序列为aaabbba,则感染。患者2的DNA序列为babbba,则未感染。(注意:人的DNA序列是线性的,而病毒的DNA序列是环状的)。

下面分别展示BF算法以及KMP算法的实现

注:KMP算法理解起来比较困难,若想简单理解原理,则可参考天勤的讲解

BF算法:

#include <iostream>
#include <string>
using namespace std;

int index_BF(const string &str1, const string &str2, int pos);

int main(){
	int pos = 0;
	string str1,str2;
	while(cin >> str2 >> str1){
		if(str1 == "0" || str2 == "0")break;
		int result = index_BF(str1,str2,pos);
		if(result != -1){
			cout << "YES " << result << endl;
		}
		else{
			cout << "NO" << endl;
		}
		}
	}

int index_BF(const string &str1, const string &str2, int pos){
	int i = pos;
	int j= 0;
	int len1 = str1.size();
	int len2 = str2.size();
	while(i<len1 && j<len2){
		if(str1[i] == str2[j]){
			i++;
			j++;
		}
		else{
			i = i - j + 1;
			j = 0;
		}
	}
	if(j >= len2)
		return i-len2;
	else
		return -1;

}

KMP算法:

 #include<iostream>
 #include<cstring>
 #include<string>
 #include<fstream>
 using namespace std;
 
 void get_next(string str2,int *next)
 {
     int i,j;
     i=1;
     j=0;
     next[1]=0;
     while(i<str2.size())
     {
         if(j==0||str2[i]==str2[j])
         {
             ++i;
             ++j;
             if(str2[i]!=str2[j])
                 next[i]=j;
             else
                 next[i]=next[j];
         }
         else
             j=next[j];
     }
 }
 
 int kmp(string &str1,string &str2,int pos)
 {
 
     int i=pos;
     int j=0;
     int next[255];
     get_next(str2,next);
     int len1=str1.size();
     int len2=str2.size();
     while(i<len1&&j<len2)
     {
         if(j==0||str1[i]==str2[j])
         {
             i++;
             j++;
         }
         else
         {
             j=next[j];
         }
     }
         if(j>=len2)
             return i-len2;
         else
             return -1;
 }
 
 int main()
 {
     int pos=0    ;
     string str1;
     string str2;
     while(cin >>str2>>str1)
     {
         if(str1=="0"&&str2=="0")break;
     int result=kmp(str1,str2,pos);
     if(result!=-1)
         cout<<"YES"<<endl;
     else
         cout<<"NO"<<endl;
     }
     return 0;
 }

更多推荐