Given a string text, we are allowed to swap two of the characters in the string. Find 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", which its length is 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", which its length is 6.


Example 3:

Input: text = "aaabbaaa"
Output: 4


Example 4:

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


Example 5:

Input: text = "abcdef"
Output: 1


Constraints:

• 1 <= text.length <= 20000
• text consist of lowercase English characters only.

Solution: HashTable

Pre-processing

1. Compute the longest repeated substring starts and ends with text[i].
2. Count the frequency of each letter.

Main

1. Loop through each letter
2. Check the left and right letter
• if they are the same, len = left + right
• e.g1. “aa c aaa [b] aaaa” => len = 3 + 4 = 7
• if they are not the same, len = max(left, right)
• e.g2. “aa [b] ccc d c” => len = max(2, 3) = 3
3. If the letter occurs more than len times, we can always find an extra one and swap it with the current letter => ++len
• e.g.1, count[“a”] = 9 > 7, len = 7 + 1 = 8
• e.g.2, count[“c”] = 4 > 3, len = 3 + 1 = 4

Time complexity: O(n)
Space complexity: O(n)

C++

If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website

Paypal
Venmo
huahualeetcode

Be First to Comment

Mission News Theme by Compete Themes.