首先,大家得理解题意,子串长度是固定的,因此要使子串中GC-Ratio最大,只需子串中的GC数量达到最大即可,不需要去计算比例。
思路:使用双指针维护一个长度固定的子串,逐步向后遍历,类似于滑动窗口,每加入一个字符,更新子串GC的数量,并记录位置,遍历完毕整个序列即可得到最大GC比例的子串出现的位置。整个思路和双端队列的解题思路是类似的。
#include <stdio.h>
int main(void)
{
char DNA_str[100000] = {0};
int len;
int GC_cnt;//记录子串GC的数量
int max_GC_num;//记录子串GC的最大数量
int max_GC_pos;//记录子串中GC数量最大时,子串的位置,方便输出
int sub_str_len;//子串长度
int i, j;
while((gets(DNA_str)) != NULL){
scanf("%d",&sub_str_len);
len = strlen(DNA_str);
GC_cnt = 0;
for(i = 0; i < sub_str_len;i++){
if(DNA_str[i] == 'G' || DNA_str[i] == 'C'){
GC_cnt++;
}
}
max_GC_num = GC_cnt;
max_GC_pos = 0;
i = 1;
j = sub_str_len;
for(; j < len;i++,j++){
if(DNA_str[i-1] == 'G' || DNA_str[i-1] == 'C'){
GC_cnt--;
}
if(DNA_str[j] == 'G' || DNA_str[j] == 'C'){
GC_cnt++;
}
if(max_GC_num < GC_cnt){
max_GC_num = GC_cnt;
max_GC_pos = i;
}
}
for(int i = max_GC_pos; i < max_GC_pos+sub_str_len;i++){
printf("%c",DNA_str[i]);
}
printf("\n");
memset(DNA_str,0,100000);
}
}


京公网安备 11010502036488号