<p>You are given a string <code>text</code>. You can swap two of the characters in the <code>text</code>.</p>

<p>Return <em>the length of the longest substring with repeated characters</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> text = &quot;ababa&quot;
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can swap the first &#39;b&#39; with the last &#39;a&#39;, or the last &#39;b&#39; with the first &#39;a&#39;. Then, the longest repeated character substring is &quot;aaa&quot; with length 3.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> text = &quot;aaabaaa&quot;
<strong>Output:</strong> 6
<strong>Explanation:</strong> Swap &#39;b&#39; with the last &#39;a&#39; (or the first &#39;a&#39;), and we get longest repeated character substring &quot;aaaaaa&quot; with length 6.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> text = &quot;aaaaa&quot;
<strong>Output:</strong> 5
<strong>Explanation:</strong> No need to swap, longest repeated character substring is &quot;aaaaa&quot; with length is 5.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= text.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>text</code> consist of lowercase English characters only.</li>
</ul>

class Solution:
    def maxRepOpt1(self, text: str) -> int:
        if len(text) <= 2: return len(text)
        
        islands = []
        
        curr = ''
        curr_count = 0
        for ch in [*text, "-"]:
            if ch == curr:
                curr_count += 1
            else:
                if curr_count > 0:
                    islands.append((curr, curr_count))
                curr = ch
                curr_count = 1
        # print(islands)
        
        best = -1
        for i in range(len(islands) - 2):
            l, m, r = islands[i], islands[i+1], islands[i + 2]
            rest = [isl[0] for isl in islands[:i]] 
            if i + 3 in range(len(islands)):
                rest.extend([isl[0] for isl in islands[i+3:]])
            
            if l[0] == r[0]:
                if l[0] in rest:
                    if m[1] == 1:   best = max(best, l[1] + r[1] + 1)
                    else: best = max(best, max(l[1], r[1]) + 1)
                else:
                    if m[1] == 1:
                        best = max(best, l[1] + r[1])
                    else:
                        best = max(best, max(l[1], r[1]) + 1)
            else:
                if l[0] in rest:
                    best = max(best, l[1] + 1)
                if r[0] in rest:
                    best = max(best, r[1] + 1)
                
                best = max(best, max(l[1], r[1]))
            
        if best == -1:
            return max([i[1] for i in islands])
        return best
18600