题目来源:
https://www.nowcoder.com/questionTerminal/e8480ed7501640709354db1cc4ffd42a?toCommentId=140458
题目描述:
一个DNA序列由A/C/G/T四个字母的排列组合组成。G和C的比例(定义为GC-Ratio)是序列中G和C两个字母的总的出现次数除以总的字母数目(也就是序列长度)。在基因工程中,这个比例非常重要。因为高的GC-Ratio可能是基因的起始点。
给定一个很长的DNA序列,以及要求的最小子序列长度,研究人员经常会需要在其中找出GC-Ratio最高的子序列。
测试用例:
输入一个string型基因序列,和int型子串的长度
找出GC比例最高的子串,如果有多个输出第一个的子串
输入
AACTGTGCACGACCTGA
5
输出
GCACG
思想:
本题相当于遍历字符串,以每个下标为开始,进行提取子串。
然后相当于找最大值一样,依次打擂台。找到最大值的GC比例。
这里有一个逻辑上的难点,那就是给定了dna序列,和子串长度,需要遍历几次?
我们来举个栗子分析一哈~~
最后一个子串的下标为:dna序列的长度-子串个数
代码:
import java.util.*;
public class Main {
//返回一个字符串的GC比例
public static double GiveRatio(String str) {
int count=0;
double ratio=0;//这里要用double型,如果用int型,2/5的结果为0
/*
for(char ch : str.toCharArray()){
if(ch=='G' || ch=='C') {
count++;
}
}*/
char[] c=str.toCharArray();
if(c[count]=='C'||c[count]=='G') {
for (; count < str.length(); count++) {
}
}
radio=count/(double)str.length();
return radio;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String dna=scanner.nextLine();//String型基因序列
int usedSized=scanner.nextInt();//int型子串长度
String maxstr=" ";//记录比例最高的字符串
double maxradio=0.0;//记录最高比例
//最后一个子串的下标:i=dna.length()-usedSized
for(int i=0;i<=dna.length()-usedSized;i++){
//用substring()每次截取长度为usedSized的子串
String str=dna.substring(i,i+usedSized);//截取子串的起始点i,结束点为i+usedSized
if(giveRatio(str)>maxradio){
maxstr=str;
maxradio=giveRatio(maxstr);
}
}
System.out.println(maxstr);
}
}