题解 | #编程题2#

编程题2

https://www.nowcoder.com/practice/dcc301bc11a7420b88afdbd272299809

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);

        while(in.hasNext()){
            solution(in);
        }
    }

    /**
     * 滑动窗口
     */
    private static void solution(Scanner in){
        int n = in.nextInt();
        int m = in.nextInt();
        String s = in.next();

        int countA = 0;
        int countB = 0;
        int max = 0;
        for(int left=0, right=0; left<=right&&right<n;){
            if(Math.min(countA, countB) <= m){
                max = Math.max(max, right-left);

                if(s.charAt(right++) == 'a'){
                    countA++;
                }else{
                    countB++;
                }
            }else{
                if(s.charAt(left++) == 'a'){
                    countA--;
                }else{
                    countB--;
                }
            }
        }

        System.out.println(max);
    }
}

全部评论

相关推荐

大摆哥:刚好要做个聊天软件,直接让你帮他干活了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务