Swap For Longest Repeated Character Substring — LeetCode 1156 Python Solution
MediumHash TableStringSliding Window
- Problem
- #1156
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a string text. You can swap two of the characters in the text.
Example
- 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.
Python solution
Python
class Solution:
def maxRepOpt1(self, text: str) -> int:
cnt = Counter(text)
n = len(text)
ans = i = 0
while i < n:
j = i
while j < n and text[j] == text[i]:
j += 1
l = j - i
k = j + 1
while k < n and text[k] == text[i]:
k += 1
r = k - j - 1
ans = max(ans, min(l + r + 1, cnt[text[i]]))
i = j
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(C) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1156. Swap For Longest Repeated Character Substring is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
LeetCode 3Longest Substring Without Repeating CharactersMediumLeetCode 30Substring with Concatenation of All WordsHardLeetCode 76Minimum Window SubstringHardLeetCode 187Repeated DNA SequencesMediumLeetCode 395Longest Substring with At Least K Repeating CharactersMediumLeetCode 424Longest Repeating Character ReplacementMedium
Frequently asked questions
- How hard is LeetCode 1156. Swap For Longest Repeated Character Substring?
- LeetCode 1156. Swap For Longest Repeated Character Substring is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1156. Swap For Longest Repeated Character Substring?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1156. Swap For Longest Repeated Character Substring?
- The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 1156. Swap For Longest Repeated Character Substring cover?
- LeetCode 1156. Swap For Longest Repeated Character Substring is tagged Hash Table, String and Sliding Window on LeetCode.