<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:
        min_idx_occ = dict()
        max_idx_occ = dict()
        for i in range(len(text)):
            c = text[i]
            max_idx_occ[c] = i
        for i in range(len(text) - 1, -1, -1):
            c = text[i]
            min_idx_occ[c] = i
                    
        def process(c):
            longest = 0
            lo, hi = 0, 0
            other = 0
            other_c = deque()
            while hi < len(text):
                if text[hi] != c:
                    other += 1
                    other_c.append(text[hi])
                while lo <= hi and other > 1:
                    if text[lo] != c:
                        other_c.popleft()
                        other -= 1
                    lo += 1
                if other == 1:
                    oc = other_c[0]
                    if min_idx_occ[c] < lo or max_idx_occ[c] > hi:
                        longest = max(longest, hi - lo + 1)
                else:
                    longest = max(longest, hi - lo + 1)
                hi += 1
            return longest
        
        res = 0
        
        for cord in range(ord('a'), ord('z') + 1):
            c = chr(cord)
            if c in min_idx_occ:
                res = max(res, process(c))
            
        return res
16400