Java | Leetcode Java题解之第424题替换后的最长重复字符

题目:

题解:

java 复制代码
public class Solution {

    public int characterReplacement(String s, int k) {
        int len = s.length();
        if (len < 2) {
            return len;
        }

        char[] charArray = s.toCharArray();
        int left = 0;
        int right = 0;

        int res = 0;
        int maxCount = 0;
        int[] freq = new int[26];
        // [left, right) 内最多替换 k 个字符可以得到只有一种字符的子串
        while (right < len){
            freq[charArray[right] - 'A']++;
            // 在这里维护 maxCount,因为每一次右边界读入一个字符,字符频数增加,才会使得 maxCount 增加
            maxCount = Math.max(maxCount, freq[charArray[right] - 'A']);
            right++;

            if (right - left > maxCount + k){
              	// 说明此时 k 不够用
                // 把其它不是最多出现的字符替换以后,都不能填满这个滑动的窗口,这个时候须要考虑左边界向右移动
                // 移出滑动窗口的时候,频数数组须要相应地做减法
                freq[charArray[left] - 'A']--;
                left++;
            }
            res = Math.max(res, right - left);
        }
        return res;
    }
}
相关推荐
Billlly9 分钟前
ABC 453 个人题解
算法·题解·atcoder
java1234_小锋1 小时前
Java高频面试题:Springboot的自动配置原理?
java·spring boot·面试
末央&2 小时前
【天机论坛】项目环境搭建和数据库设计
java·数据库
枫叶落雨2222 小时前
ShardingSphere 介绍
java
花花鱼2 小时前
Spring Security 与 Spring MVC
java·spring·mvc
小白菜又菜2 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
言慢行善3 小时前
sqlserver模糊查询问题
java·数据库·sqlserver
专吃海绵宝宝菠萝屋的派大星3 小时前
使用Dify对接自己开发的mcp
java·服务器·前端
大数据新鸟3 小时前
操作系统之虚拟内存
java·服务器·网络
Tong Z3 小时前
常见的限流算法和实现原理
java·开发语言