Swap For Longest Repeated Character Substring - Problem
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.
A substring is a contiguous sequence of characters within a string. After swapping two characters, you need to find the longest substring where all characters are the same.
Input & Output
Example 1 — Basic Case
$
Input:
text = "ababa"
›
Output:
3
💡 Note:
We can swap the second 'b' with the last 'a' to get "aabaa", then the longest substring with repeated characters is "aaa" with length 3.
Example 2 — All Same Characters
$
Input:
text = "aaaa"
›
Output:
4
💡 Note:
All characters are already the same, so no swap is needed. The entire string "aaaa" has length 4.
Example 3 — Two Different Characters
$
Input:
text = "abab"
›
Output:
3
💡 Note:
We can swap one 'b' with one 'a' to get "aaab" or "abaa", giving us a longest repeated substring of length 3.
Constraints
- 1 ≤ text.length ≤ 1000
- text consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
String "ababa" - need to find best swap
2
Process
Try swapping characters to maximize repeated substring
3
Output
Return length 3 (longest possible after one swap)
Key Takeaway
🎯 Key Insight: Use sliding window to find longest substring with at most one character different from target
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code