解题思路: 滑动窗口

  • 给出了固定的子串长度;
  • 根据题意, 要查询出 在这个子串中 CG数量最多的第一个子串, 那就需要一个index来存储子串的起始位置。 还需记录随着窗口的移动count的变化, count与max的大小比较之后 更新index的值。
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) { // 注意 while 处理多个 case
            int index = 0;
            int count = 0;
            int max;
            
            String str = in.next();
            int n = in.nextInt();

            // 初始化:得到前N个子串中 CG 出现的次数
            // 这个for的初始化操作也可以直接省略。 因为后期存在对count的加减操作, 加会改变index,减去就是后面所有的子串都没有从0开始的长。
            int right = n;
            for (int i = 0; i < n; i++) {
                if (str.charAt(i) == 'C' || str.charAt(i) == 'G') {
                    count += 1;
                }
            }
            max = count;

            for (int left = 1; left < right; left++) {
                if (right < str.length()) {
                    // 窗口新的有边界  +1
                    if (str.charAt(right) == 'C' || str.charAt(right) == 'G') {
                        count++;
                    }
                    // 窗口的滑走的左边界, 失去1个
                    if (str.charAt(left - 1) == 'C' || str.charAt(left - 1) == 'G') {
                        count--;
                    }
                    if (count > max) {
                        max = count;
                        index = left;
                    }
                    right++;
                }

            }

            System.out.println(str.substring(index, index + n));
        }
    }
}