# Longest Repeating Character Replacement LeetCode Solution

Here, We see Longest Repeating Character Replacement LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations.

Example 1:
Input: s = “ABAB”, k = 2
Output: 4
Explanation: Replace the two ‘A’s with two ‘B’s or vice versa.

Example 2:
Input: s = “AABABBA”, k = 1
Output: 4
Explanation: Replace the one ‘A’ in the middle with ‘B’ and form “AABBBBA”. The substring “BBBB” has the longest repeating letters, which is 4. There may exists other ways to achieve this answer too.

## Longest Repeating Character Replacement LeetCode Solution C++

``````class Solution {
public:
int characterReplacement(string s, int k) {
int n = s.size();
int i = 0, j = 0, maxi = 0;
unordered_map<char,int>mp;
int ans = -1;
while(j < n)
{
mp[s[j]]++;
maxi = max(maxi, mp[s[j]]);
if((j-i+1) - maxi > k){
mp[s[i]]--;
i++;
}
ans = max(ans, (j-i+1));
j++;
}
return ans;
}
};```Code language: PHP (php)```

## Longest Repeating Character Replacement Solution Java

``````class Solution {
public int characterReplacement(String s, int k)
{
int[] count=new int[26];
int i=0,j=0,max=Integer.MIN_VALUE;
int result=Integer.MIN_VALUE;
while(i<s.length())
{
count[s.charAt(i)-'A']++;
max=Math.max(max,count[s.charAt(i)-'A']);
if(i-j-max+1>k)
{
count[s.charAt(j)-'A']--;
j++;
}
result=Math.max(result,i-j+1);
i++;
}
return result;
}
}```Code language: JavaScript (javascript)```

## Longest Repeating Character Replacement Solution JavaScript

``````var characterReplacement = function(s, k) {
var map = [26]
let largestCount = 0, beg = 0, maxlen = 0;
for(let end = 0; end < s.length; end++){
const c = s[end]
map[c] = (map[c] || 0) + 1
largestCount = Math.max(largestCount, map[c])
if(end - beg + 1 - largestCount > k){
map[s[beg]] -= 1
beg += 1
}
maxlen = Math.max(maxlen, end - beg + 1);
}
return maxlen;
};```Code language: JavaScript (javascript)```

## Longest Repeating Character Replacement Solution Python

``````class Solution(object):
def characterReplacement(self, s, k):
maxlen, largestCount = 0, 0
arr = collections.Counter()
for idx in xrange(len(s)):
arr[s[idx]] += 1
largestCount = max(largestCount, arr[s[idx]])
if maxlen - largestCount >= k:
arr[s[idx - maxlen]] -= 1
else:
maxlen += 1
return maxlen``````
Scroll to Top