424. Longest Repeating Character Replacement

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;
    }
}

 

你可能感兴趣的:(LEETCODE,Java)