題目來源:
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);
}
}