题解 | #DNA序列#
DNA序列
http://www.nowcoder.com/practice/e8480ed7501640709354db1cc4ffd42a
使用滑动窗口解决,维护一个长度大小固定为N的窗口
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String DNA = sc.nextLine();
int N = sc.nextInt();
String gc = maxGC(DNA, N);
System.out.println(gc);
}
}
//使用滑动串口解决,滑动窗口大小固定为N
public static String maxGC(String DNA, int N){
if(N >= DNA.length()){
return DNA;
}
int g = 0, c = 0;//分别表示G和C的数目
//初始化滑动窗口
int left = 0, right = 0;
double maxGCRate = 0.0;
String gc = "";
while(right < N){
if(DNA.charAt(right) == 'G'){
g++;
}else if(DNA.charAt(right) == 'C'){
c++;
}
right++;
}
while(right < DNA.length()){
double gcRate = (g + c) * 1.0 / N;
if(gcRate > maxGCRate){
maxGCRate = gcRate;
gc = DNA.substring(left, left + N);
}
if(DNA.charAt(left) == 'G'){
g--;
}else if(DNA.charAt(left) == 'C'){
c--;
}
left++;
if(DNA.charAt(right) == 'G'){
g++;
}else if(DNA.charAt(right) == 'C'){
c++;
}
right++;
}
return gc;
}
}