Longest Repeating Character Replacement in C++


Suppose we have given a string s that consists of only uppercase letters, we can perform at most k operations on that string. In one operation, we can select any character of the string and change it to any other uppercase letters. We have to find the length of the longest sub-string containing all repeating letters we can get after performing the above operations. So if the input is like: “ABAB” and k = 2, then the output will be 4. This is because two ‘A’s with two ‘B’s or vice versa.

To solve this, we will follow these steps −

  • maxCount := 0, ans := 0 and n := size of the string s
  • make an array cnt of size 26, and j := 0
  • for i := 0 to n – 1
    • increase cnt[s[i] – ‘A’] by 1
    • maxCount := max of maxCount, count[s[i] – ‘A’]
    • while j <= i and i – j + 1 – maxCount > k, do
      • decrease cnt[s[j] – ‘A’]
      • increase j by 1
    • ans := max of ans, i – j + 1
  • return ans

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int characterReplacement(string s, int k) {
      int maxCount = 0;
      int ans = 0;
      int n = s.size();
      vector <int> cnt(26);
      int j = 0;
      for(int i = 0; i < n; i++){
         cnt[s[i] - 'A']++;
         maxCount = max(maxCount, cnt[s[i] - 'A']);
         while(j <= i && i - j + 1 - maxCount > k){
            --cnt[s[j] - 'A'];
            j++;
         }
         ans = max(ans, i - j + 1);
      }
      return ans;
   }
};
main(){
   Solution ob;
   cout << ob.characterReplacement("ABAB", 2);
}

Input

"ABAB"
2

Output

4

Updated on: 28-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements