424. Longest Repeating Character Replacement

1. Description

Given an string only containing uppercase English letters, and an integer k, which represents you can replace any letter in the string 

with another letter at most k times. Find the longest substring consists of same letters.

 

2. Solution

Slide Window.

What is sure is that the answer is at least k+1.

First, use a map to count the number of the first k+1 letters in the string.

Then, enter a loop, the loop start at the k+1 position in the string.

In one loop, add up the current letter to the map, and find whether the diff between the numbers of letters in the range and the numbers of the most common letter in the map

is less or equal to k.

If it's true, update the answer to the maximum of the original answer and  the numbers of letters in the range.

Otherwise, move the left point to the right, until the range can be changed into string with same letters with at most k replacement.


3. Code

    int characterReplacement(string s, int k) {
        int n = s.size();
        if(n<=k+1) return n;
        mapm;
        for(int i=0;im,int k){
        int big = 0;
        int sum = 0;
        for(int i=0;i<26;i++){
            sum+=m[i+'A'];
            big = max(big,m[i+'A']);
        }
        int diff = sum-big;
        if(diff<=k) return true;
        else return false;
        
    }


你可能感兴趣的:(刷题笔记,Array,Hash,Table,Slide,Window)