Longest Repeating Character Replacement

Medium

Description

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.

Examples

Input:s = "ABAB", k = 2
Output:4
Explanation:

Replace two 'A's with 'B's or vice versa.

Input:s = "AAABBBCCC", k = 2
Output:5
Explanation:

It is possible to replace 2 'C's with 'B's to get "AAABBBBB", creating a substring "BBBBB" of length 5. Alternatively, one could replace 2 'A's with 'B's to get "BBBBBCCC", creating substring "BBBBB" of length 5.

Input:s = "XYXYXYXY", k = 3
Output:5
Explanation:

It is possible to replace 3 'Y's with 'X's. The optimal approach is to target a substring like "XYXYX" and replace the 2 'Y's to get "XXXXX", giving us length 5. With k=3, there are enough operations but only need 2 to achieve the maximum length of 5.

Constraints

  • 1 ≤ s.length ≤ 10⁵
  • s consists of uppercase English letters.
  • 0 ≤ k ≤ s.length

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!