> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/hashmap-and-hashset-and-sliding-window/swap-for-longest-repeated-character-substring.md).

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

```java
/*
At each character, check if it is the same as the previous character.
If yes,   Increment curr counter by 1.
If no,    Try to skip one character and continue expanding.
          If curr counter is less than the total number of occurences of character in
		  entire string, increment curr counter by 1.
		  Answer = max(Answer, curr counter)
*/
class Solution {
    public int maxRepOpt1(String text){
        StringBuilder str=new StringBuilder(text);
        return Math.max(helper(text),helper(str.reverse().toString()));
    }
    public int helper(String text) {
        HashMap<Character, Integer> map = new HashMap<>();
        for (char c : text.toCharArray())
            map.put(c, map.getOrDefault(c, 0) + 1);
        int currCount = 0, maxLen = 0;
        char previousChar = ' ';
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == previousChar)
                currCount++;
            else {
                // if all the occurrences of the previousChar are not covered
                // then we can try to skip one char and look for remaining continuously
                if (map.containsKey(previousChar) && currCount != map.get(previousChar)) {
                    // Increasing count by 1 assuming that we will swap ith char with remaining
                    // previousChar's occurrences
                    currCount++;
                    int j = i + 1;
                    while (j < text.length() && text.charAt(j++) == previousChar)
                        currCount++;
                    // If all the remaining previousChar's occurrences are
                    // continously present after ith char
                    // then we will overshoot by 1,
                    // because we are increasing by 1 in the starting of this loop
                    if (currCount == map.get(previousChar) + 1)
                        currCount--;
                }
                maxLen = Math.max(maxLen, currCount);
                // Resetting for the new character
                currCount = 1;
                previousChar = text.charAt(i);
            }
            maxLen = Math.max(maxLen, currCount);
        }
        return maxLen;
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mayanktyagi3111.gitbook.io/interview-prep/hashmap-and-hashset-and-sliding-window/swap-for-longest-repeated-character-substring.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
