此题用滑动窗口的思想很好解决。
index是目标下标,maxGC实际上就是滑动窗口里面G,C数量最多的值
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int len = sc.nextInt(); int index = 0; int maxGC = 0; for(int i = 0;i<s.length()-len;i++){ int currentGC = 0; for(int j = i;j<len+i;j++){ if(s.charAt(j)=='G'||s.charAt(j)=='C'){ currentGC++; if(currentGC>maxGC){ index = i; maxGC = currentGC; } } } } System.out.println(s.substring(index,index+len)); } }