424. Longest Repeating Character Replacement

本文介绍了一个算法问题,即如何在给定的字符串中,通过替换最多k个字符,找到包含重复字母的最长子串。使用双指针技巧,结合数组记录字符出现频率,有效地解决了这一挑战。

Given a string s that consists of only uppercase English letters, you can perform at most k operations on that string.

In one operation, you can choose any character of the string and change it to any other uppercase English character.

Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.

Note:
Both the string's length and k will not exceed 104.

Example 1:

Input:
s = "ABAB", k = 2

Output:
4

Explanation:
Replace the two 'A's with two 'B's or vice versa.
 

Example 2:

Input:
s = "AABABBA", k = 1

Output:
4

Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-repeating-character-replacement
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 次。在执行上述操作后,找到包含重复字母的最长子串的长度。

 

双指针,用一个值保存,在前后指针中的数组出现最多的次数。

class Solution {
    public int characterReplacement(String s, int k) {
        if (s.length() == 0) {
            return 0;
        }
        int []count = new int[26];
        int maxCharNum = 0;
        int ans = 0;
        int start = 0;

        count[s.charAt(0) - 'A']++;
        maxCharNum = 1;
        for (int tail = 1; tail < s.length(); tail++) {
            count[s.charAt(tail) - 'A']++;
            maxCharNum = Math.max(maxCharNum, count[s.charAt(tail) - 'A']);
            // 前后指针构成的数组中,如果大小比maxCharNum还大k,那么后指针就向前挪位置。
            if (tail - start + 1 - maxCharNum > k) {
                count[s.charAt(start) - 'A']--;
                start++;
            } else {
                ans = Math.max(ans, tail - start + 1);
            }
        }
        return ans;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值