描述:
用一个字符串表示一段基因,例如:“CTATGGGTTT”。两段基因的相似度定义为它们所包含的最大公共子串的长度。例如:“CCTTGG”和“TGGGC”的最大公共子串为“TGG”,它的长度为3,则我们称“CCTTGG”和“TGGGC”的相似度为3。现给定两段基因,要求计算它们的相似度。
关于输入:
输入第一行包含一个正整数N...........
关于输出:
对于每组测试数据输出一行,该行包含一个整数,表示给定基因段的相似度。
输入:
2
CCCCC TTTTTGGGGGCC
ACTGGG DDD
输出:
2
0
关于C++中substr函数用法介绍:
1.需要定义一个string类型的字符串,为其赋值的方法与c中字符型数组类似。
char first[100] = "hello";
puts(first);
string first = "hello";
2
.substr()函数:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
using namespace std;
int main()
{
string first = "hello"; //也可以直接写成string first;(由输入来进行赋值)
cin >> first; //substr(pos,count),pos表示从哪一个位置开始截取,count表示截取的长度.
cout << first.substr(1) << endl; //当substr()函数只有一个参数时,默认其是为pos参数赋值,它表示从first[pos]一直截取到字符串末尾处.
cout << first.substr(4) << endl; //运行结果为:"o";
cout << first.substr(5) << endl; //运行结果为:" ";(其读取到了字符串的'\0'字符,并输出.
cout << first.substr(6) << endl; //运行结果为:编译报错substr函数会抛出一个out_of_range异常.
cout << first.substr(0,3) << endl; //表示从pos = 0开始截取,往后3个位置.故运行结果为:"hel";
cout << first.substr(1,3) << endl; //运行结果为:"ell";
return 0;
}
实现代码:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
string first;
string second;
int t,i,j,z,max,ans;
cin >> t;
while(t--)
{
ans = 0;
max = 0;
cin >> first;
cin >> second;
int len = first.length();
for(i = 0;first[i] != '\0'; i++)
{
for(z = len - i;z > 0; z--)
{
for(j = 0;second[j] != '\0'; j++)
{
if(first.substr(i,z) == second.substr(j,z))
{
ans = z;
if(ans > max)
max = ans;
}
}
}
}
printf("%d\n",max);
}
return 0;
}