[LeetCode]424. Longest Repeating Character Replacement

来源:互联网 发布:淘宝卖家怎么进货渠道 编辑:程序博客网 时间:2024/06/06 00:43

https://leetcode.com/problems/longest-repeating-character-replacement/#/description

给一个字符串,可以删除最多k个字符,求删除后的最长连续相同字符的子串











外层end遍历,找到当前start ~ end的占多数的字符有多少个,然后调整start,update最大长度

public class Solution {    public int characterReplacement(String s, int k) {        // 最大子字符串长度        int maxLen = 0;        // start ~ end 子串之中数量最多的字符有多少个        int maxCount = 0;        int start = 0;        int[] count = new int[26];        // 遍历end        for (int end = 0; end < s.length(); end++) {            maxCount = Math.max(maxCount, ++count[s.charAt(end) - 'A']);            // 移动start直到满足要求            while (end - start + 1 - maxCount > k) {                count[s.charAt(start) - 'A']--;                start++;            }            maxLen = Math.max(maxLen, end - start + 1);        }        return maxLen;    }}


0 0
原创粉丝点击