# 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:

```class Solution {
public int maxRepOpt1(String text) {
List<List<Integer>>[] list = new List[26];
for (int i = 0; i < 26; i ++) {
list[i] = new ArrayList();
}
char prev = text.charAt(0);
int count = 1;
for (int i = 1; i < text.length(); i ++) {
char c = text.charAt(i);
if (c == prev) {
count ++;
} else {
list[prev - 'a'].add(Arrays.asList(count, i - count, i - 1));
count = 1;
}
prev = c;
}
list[prev - 'a'].add(Arrays.asList(count, text.length() - count, text.length() - 1));
int max = 0;
for (List<List<Integer>> l : list) {
List<Integer> pre = null;
for (List<Integer> cur : l) {
// System.out.println(l);
max = Math.max(max, cur.get(0) + (l.size() > 1 ? 1 : 0));
if (pre != null && pre.get(2) + 2 == cur.get(1)) {
max = Math.max(max, pre.get(0) + (l.size() > 2 ? 1 : 0) + cur.get(0));
}
pre = cur;
}
}
return max;
}
}```