从左往右遍历字符串,每次取长度为n的子串出来,统计子串中CG的数量,与当前的最大数量做比较,如果大于当前的,就更新CG的最大数量值及子串起始位置,遍历完成后,输出从起始位置开始的长度为n的子串即可
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int n = Integer.valueOf(br.readLine());
int max = 0;
int start = 0;
for(int i = 0; i < s.length() - n; i++) {
String t = s.substring(i, i+n);
int count = Main.countCG(t);
if (max < count) {
max = count;
start = i;
}
}
System.out.println(s.substring(start, start + n));
}
public static int countCG(String s) {
int count = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == 'C' || s.charAt(i) == 'G') {
count++;
}
}
return count;
}
}

京公网安备 11010502036488号