题解 | 滑动窗口

编程题2

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

import java.util.*;
/**
滑动窗口 本题就是寻找全换成a或者全换成b哪个最长 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        String s = sc.next();
        System.out.println(Math.max(fun(new HashMap<>(),'a',s,m),fun(new HashMap<>(),'b',s,m)));
    }

    private static int fun(Map<Character, Integer> map, char r, String s, int m) {
        //先初始化a和b的字符都为0 防止空指针
        map.put('a',0);
        map.put('b',0);
        int res = 0;
        if (r == 'a') {
            int left = 0;
            int right = 0;
            while (right < s.length()) {
                //增大窗口
                char c = s.charAt(right);
                map.put(c, map.get(c)+ 1);
                right++;
                //如果这时候b的字符数量超过了最大可以替换的次数就缩小窗口
                while (map.get('b') > m) {
                    char d = s.charAt(left);
                    map.put(d, map.get(d)-1);
                    left++;
                }
                res = Math.max(res, right - left);
            }
        } else {
            int left = 0;
            int right = 0;
            while (right < s.length()) {
                char c = s.charAt(right);
                map.put(c,map.get(c)+ 1);
                right++;
                while (map.get('a') > m) {
                    char d = s.charAt(left);
                    map.put(d,map.get(d)-1);
                    left++;
                }
                res = Math.max(res, right - left);
            }
        }
        return res;
    }
}

全部评论

相关推荐

11-28 17:48
中山大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务