- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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
- Related Articles
- Longest Repeating Substring in C++
- Maximum consecutive repeating character in string in C++
- Check for Palindrome after every character replacement Query in C++
- Longest Substring with At Least K Repeating Characters in C++
- Longest Substring Without Repeating Characters in Python
- Find the last non repeating character in string in C++
- Swap For Longest Repeated Character Substring in C++
- First non-repeating character using one traversal of string in C++
- Finding first non-repeating character JavaScript
- Find first repeating character using JavaScript
- Integer Replacement in C++
- Return index of first repeating character in a string - JavaScript
- What are repeating character classes used in Python regular expression?
- Finding the longest Substring with At Least n Repeating Characters in JavaScript
- Program to find length of longest repeating substring in a string in Python

Advertisements