Talentd
FleetCode

1156. Swap For Longest Repeated Character Substring

Medium44.9% acceptance2 companies

You are given a string text. You can swap two of the characters in the text.

Return the length of the longest substring with repeated characters.

Example 1:

Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3.

Example 2:

Input: text = "aaabaaa"
Output: 6
Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6.

Example 3:

Input: text = "aaaaa"
Output: 5
Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.

Constraints:

  • 1 <= text.length <= 2 * 104
  • text consist of lowercase English characters only.

Asked at 2 companies

Hints open one at a time

Hint 1
There are two cases: a block of characters, or two blocks of characters between one different character. By keeping a run-length encoded version of the string, we can easily check these cases.
10:36
Still stuck?Read 4 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def maxRepOpt1(self, text: str) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
"ababa"
Input
"aaabaaa"
Input
"aaaaa"
Your code is saved on this device.Solution