characterReplacement-the longest repeated character after replacement

Title description

Give you a string consisting of only uppercase English letters. You can replace the character at any position with another character, and you can replace it up to k times in total. After performing the above operations, find the length of the longest substring containing repeated letters.

Note: The length of the string and k will not exceed 104.

Example 1:

Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace two'A's with two'B's , and vice versa.

Example 2:

Input: s = "AABABBA", k = 1
Output: 4
Explanation:
Replace the middle "A" with "B", and the string becomes "AABBBBA".
The substring "BBBB" has the longest repeated letter, and the answer is 4.

Related Topics Two-pointer Sliding Window

Problem-solving ideas

I have done a similar question before, to find the longest repeated string, using double pointers, right-left, and stored in a reserved field max, where max is the size of the window. The window will only be updated when max is updated. Get bigger.
1. The minimum size of the window is k+1 (generally)
2. The definition of the window is the most elements in the
window +k 3. The window slides, and the window update is not satisfied, and then continues to slide to the right. At this time, the overall window shifts
4 .The window is updated, which element is the most added element

Code demo

class Solution {
    
    
    public int characterReplacement(String s, int k) {
    
    
        //字符串的长度小于k,则返回的结果必定是s,因为都可以被替换
            if(s.length()<=k+1)
                return s.length();
            //0-A,25-Z 用来存放窗口内各个字母的数量
            int[] map=new int[26];
        char[] chars = s.toCharArray();
        int left=0,right;
        int max=0;
        for(right=0;right<s.length();right++)
        {
    
    
            //变量index存放字符的索引值
            int index=chars[right]-'A';
            //当前窗口内,该字母数量+1;
            map[index]++;
            //更新窗口内最多的字母数量
            max=Math.max(max,map[index]);
            //新增的数加入到窗口,不满足可以更新窗口的条件
            //窗口向左平移
            if(right-left+1>max+k)
            {
    
    
                //只要平移,窗内就会少一个元素,这个对应元素的数量不纳入窗内数量的统计,将数量-1;
                map[chars[left]-'A']--;
                left++;
            }

        }
         //窗户到达左右边的时候,此时的right为s.length();
        return right-left;
    }
}

running result

The info
answer was successful:
execution time: 6 ms, defeating 60.54% of Java users
Memory consumption: 38.8 MB, defeating 8.85% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/113540778