MediumNo. 1156
Swap For Longest Repeated Character Substring — LeetCode 1156 Python Solution
- Pattern
- Sliding Window
- Topics
- Hash Table, String, 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
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
- Time
- O(n)
- Space · auxiliary
- O(C)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0030 | Substring with Concatenation of All Words | Hard |
| 0076 | Minimum Window Substring | Hard |
| 0187 | Repeated DNA Sequences | Medium |
| 0395 | Longest Substring with At Least K Repeating Characters | Medium |
| 0424 | Longest Repeating Character Replacement | Medium |
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.