华为机试联系-DNA序列
DNA序列
http://www.nowcoder.com/questionTerminal/e8480ed7501640709354db1cc4ffd42a
题目描述
一个DNA序列由A/C/G/T四个字母的排列组合组成。G和C的比例(定义为GC-Ratio)是序列中G和C两个字母的总的出现次数除以总的字母数目(也就是序列长度)。在基因工程中,这个比例非常重要。因为高的GC-Ratio可能是基因的起始点。
给定一个很长的DNA序列,以及要求的最小子序列长度,研究人员经常会需要在其中找出GC-Ratio最高的子序列。
本题含有多组样例输入。
- 滑动窗口
- 两个指针 left right
- right 和left 中间包含符合要求长度的字符串
- left 左移 判断内容是否符合要求
- right 右移 判断内容是否符合要求
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String str = in.nextLine();
int len = in.nextInt();
char[] chars = str.toCharArray();
int left=0;
int right=len-1;
double GC_Radio=0.0; //当前len长字符串的比例
int count=0;//当前len长字符串内的G C 个数
StringBuilder sb=new StringBuilder();
String res=null;
//先移动窗口 到包含指定长度字符串
for(int i=0;i<right+1;i++ ){
if(chars[i]=='G'||chars[i]=='C'){
count++;
}
sb.append(chars[i]);
}
GC_Radio=(1.0*count)/len;;
res=sb.toString();
// System.out.println(right+" "+left);
while(right<chars.length-1&&(right-left+1)==len){
//left 左移 判断 如果得当前是GC 移动后计数-1
if(chars[left]=='G'||chars[left]=='C'){
count--;
}
left++;
//删除0号元素
sb.deleteCharAt(0);
right++;
//后面添加一个元素
sb.append(chars[right]);
//right右移 如果是GC 计数+1
if(chars[right]=='G'||chars[right]=='C'){
count++;
}
//当前判断大于max时, res得到当前字符串
if((1.0*count)/len > GC_Radio){
GC_Radio=(1.0*count)/len;;
res=sb.toString();
}
}
System.out.println(res);
}
}
} 

