Press "Enter" to skip to content

花花酱 LeetCode 1156. Swap For Longest Repeated Character Substring

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

Leave a Reply