Description
As an IBM researcher, you have been tasked with writing a program that will find commonalities amongst given snippets of DNA that can be correlated with individual survey information to identify new genetic markers.
A DNA base sequence is noted by listing the nitrogen bases in the order in which they are found in the molecule. There are four bases: adenine (A), thymine (T), guanine (G), and cytosine (C). A 6-base DNA sequence could be represented as TAGACC.
Given a set of DNA base sequences, determine the longest series of bases that occurs in all of the sequences.
Input
- A single positive integer m (2 <= m <= 10) indicating the number of base sequences in this dataset.
- m lines each containing a single base sequence consisting of 60 bases.
Output
Sample Input
3 2 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 3 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA GATACTAGATACTAGATACTAGATACTAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA GATACCAGATACCAGATACCAGATACCAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA 3 CATCATCATCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ACATCATCATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AACATCATCATTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
Sample Output
no significant commonalities AGATAC CATCATCAT
题意:求最长公共字符串。如果最大长度小与3,则输出no significant commonalities.反之输出最长的这个串。
分析:枚举公共字符串的长度,然后再第2到N串中找是否存在字符串1中相应长度的子串。
这里采用的是(使用朴素的模式匹配算法求最长的公共子串)
知识点整理:
1、
包含文件:string.h
函数名: strstr
函数原型:extern char *strstr(char *str1, char *str2);
功能:从字符串str1中查找是否有字符串str2,如果有,从str1中的str2位置起,返回str1中str2起始位置的指针,如果没有,返回null。
返回值:返回该位置的指针,如找不到,返回空指针。
例子:
123 char
str[]="1234
xyz";char*
str1=strstr(str,"34");cout<
显示: 34 xyz
2、
原型:extern int strcmp(const char *s1,const char * s2);
所在头文件:string.h
功能:比较字符串s1和s2。
一般形式:strcmp(字符串1,字符串2)
说明:
当s1
当s1==s2时,返回值= 0
当s1>s2时,返回值 = 1
注:c++ 中
当s1
当s1==s2时,返回值等于0
当s1>s2时,返回值 大于0
即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。如:
"A"<"B" "a">"A" "computer">"compare"
特别注意:strcmp(const char *s1,const char * s2)这里面只能比较字符串,不能比较数字等其他形式的参数。
3、
函数名: strncmp
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxm = 15;
const int maxs = 65;
int main(){
int t;
cin >> t;
while(t--)
{
int m, i, j, k, l;
int len = 0;
char ans[maxs], p[maxm][maxs], s[maxs];
cin >> m;
for(i = 0 ; i < m ; ++i)
cin >> p[i];
l = strlen(p[0]);
for(i = 0 ; i < l ; ++i)
{
for(j = i + 2 ; j < l ; ++j)
{
strncpy(s,p[0] + i,j - i + 1);//将p[0]+i位置以后的j - i + 1个字符复制到s中
s[j-i+1] = '\0';//注意,因为他是字符串,所以尽量加上'\0'
bool ok = true;
for(k = 1 ; ok && k < m ; ++k)
if(strstr(p[k],s) == NULL)
//strstr(str1,str2) :判断str1中是否含有str2
ok = false;
if(ok&& (j - i + 1 > len || (j - i + 1 == len && strcmp(ans,s) > 0)))
{
len = j - i + 1;
strcpy(ans,s);
}
}
}
if(len < 3)
printf("no significant commonalities\n");
else
printf("%s\n",ans);
}
return 0;
}