Swap For Longest Repeated Character Substring Problem
Description
LeetCode Problem 1156.
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 * 10^4textconsist of lowercase English characters only.
Solution
Approach: Runs of Equal Characters
A swap can only help in two ways:
- Extend a run of a character
cby one: bring anothercfrom somewhere else next to it. - Join two runs of
cthat are separated by exactly one other character: swap that character with acfrom elsewhere.
So we walk the string run by run. For the run text[i..j-1] of character c, of length left, we skip the one character at j and measure the run of c right after it, of length right (it is 0 if text[j + 1] is not c). The best we can build here is left + right + 1: both runs plus one more c swapped into position j (or onto the end of the run when right is 0).
That extra c has to come from somewhere. If all copies of c in the string are already in these two runs, there is none to spare, and we can only rearrange them into left + right in a row. Both cases are covered by capping the length at the total count of c: min(left + right + 1, count[c]). For example, in "aaabaaa" the two runs give 3 + 3 + 1 = 7, but there are only six as, so the answer is 6.
The answer is the largest value over all runs.
Complexity: O(n) time, since each run is scanned at most twice, and O(1) extra space for the 26 counts.
from collections import Counter
class Solution:
def maxRepOpt1(self, text: str) -> int:
cnt = Counter(text)
n = len(text)
ans = i = 0
while i < n:
# text[i..j-1] is a run of one character c.
j = i
while j < n and text[j] == text[i]:
j += 1
left = j - i
# Skip text[j] and measure the next run of c after it.
k = j + 1
while k < n and text[k] == text[i]:
k += 1
right = k - j - 1
# One more c has to come from somewhere, and we cannot use more c's than exist.
ans = max(ans, min(left + right + 1, cnt[text[i]]))
i = j
return ans