Swap For Longest Repeated Character Substring in C++


Suppose we have a string text, so we are allowed to swap two of the characters in the string. We have to find the length of the longest substring with repeated characters. So if the input is like “ababa”, then the result will be 3, as if we swap first b with last a, or the last b with first a,then the longest repeated character will be “aaa”, so the length is 3.

To solve this, we will follow these steps −

  • Define a map cnt, set ret := 1, j := 0, n := size of text, v := 0, define a set called x, and create another map called m, the m will hold the frequency of each character in text.

  • set a := * and b := *

  • for i in range 0 to n

    • increase cnt[text[i]] by 1

    • insert text[i] into x

    • if cnt[text[i]] is 2, then

      • if a is *. then a := text[i], otherwise b := text[i]

    • if a is not * and b is also not * or size of x is greater than 2

      • decrease cnt[text[j]] by 1

      • if cnt[text[j]] is 1, then

        • if text[j] is a, then set a := *, otherwise b := *

    • if cnt[text[j]] is 0, then delete text[j] from x

    • greater := a if cnt[a] > cnt[b], otherwise b

    • if size of x is 1 or m[greater] – cnt[greater] is non 0, then

      • ret := max of ret, i – j + 1

    • otherwise ret := max of ret, i – j

  • return ret.

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int maxRepOpt1(string text) {
      int ret = 1;
      map <char, int> cnt;
      int j = 0;
      int n = text.size();
      int v = 0;
      set <char> x;
      map <char, int> m;
      for(int i = 0; i < text.size(); i++)m[text[i]]++;
      char a = '*', b ='*';
      for(int i = 0; i < n; i++){
         cnt[text[i]]++;
         x.insert(text[i]);
         if(cnt[text[i]] == 2){
            if(a == '*'){
               a = text[i];
            }else{
               b = text[i];
            }
         }
         while(a != '*' && b != '*' || x.size() > 2){
            cnt[text[j]]--;
            if(cnt[text[j]] == 1) {
               if(text[j] == a) {
                  a ='*';
               }else{
                  b = '*';
               }
            }
            if(cnt[text[j]] == 0) x.erase(text[j]);
            j++;
         }
         char greater = cnt[a] > cnt[b] ? a : b;
         if(x.size() == 1 || m[greater] - cnt[greater]){
            ret = max(ret, i - j + 1);
         }else{
            ret = max(ret, i - j);
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.maxRepOpt1("ababa"));
}

Input

"ababa"

Output

3

Updated on: 30-Apr-2020

427 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements