PTA: Pattern matching of strings

topic

This question requires reading two DNA sequences A and B, where A is the human DNA sequence and B is the virus DNA sequence, and then determine whether virus B appears in A (note: the DNA sequence of the virus is circular).

Input format

Enter an integer n, and then enter n pairs of DNA sequences (each DNA sequence is a string, the length does not exceed 10000).

Output format

For each pair of DNA sequences A and B, if B appears in A, output Yes, otherwise output No

Input sample

2
AAAAAAAAACCCCGGGGTTTTTTTAGTCCCTTGGGAAATCGAAGTCGTCAAAAAAAAA

GGGGTTTTTCCCCCCAAAATTTCCCGGGTTTTTTTTTTGGGGTTT

Output sample

Yes
Yes

Ideas

  1. IsVinDNAFunction: A function that checks whether the viral DNA sequence appears in the human DNA sequence. It accepts two string parameters a and b, where a represents the human DNA sequence and b represents the viral DNA sequence.

First, the function gets the lengths of strings a and b and stores them in lena and lenb for subsequent comparison.

Then, check whether the length of the viral DNA sequence b is greater than the length of the human DNA sequence a. If so, directly return false (the viral DNA sequence cannot be included in the human DNA sequence)

Next, create a string cir (circle, ring) and connect the human DNA sequence a to itself. In fact, a circular DNA sequence is constructed.

Finally, use the find function to find whether the viral DNA sequence b appears in the circular DNA sequence cir

  1. In main, each pair of DNA sequences is processed through a loop. In each cycle, two strings s1 and s2 are read, representing the human DNA sequence and the viral DNA sequence respectively. Then call the IsVinDNA function to check whether the viral DNA sequence appears in the human DNA sequence. Finally, according to the check result, "Yes" or "No" is output.

The idea of ​​this code is to connect the human DNA sequence to itself, to construct a circular DNA sequence, and then check the viral DNA Whether the sequence occurs in this circular sequence

Precautions:

Use the find function of the string to check whether it contains a substring (strstr can be used in C language, the effect is similar)

code

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

bool IsVinDNA(const string&a,const string&b)
{
    
    
    int lena = a.length();
    int lenb = b.length();
    if(lenb > lena)
        return false;
    string cir = a+a;
    if(cir.find(b) != string::npos)
        return true;
    return false;
}
int main()
{
    
    
    int n;
    cin>>n;
    string s1,s2;
    for(int i =0 ;i<n;i++)
    {
    
    
        cin>>s1>>s2;
        if(IsVinDNA(s1,s2))
        {
    
    
            cout<<"Yes"<<endl;
        }
        else
        {
    
    
            cout<<"No"<<endl;
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_74195626/article/details/133849890