---
# System prepended metadata

title: 1156. Swap For Longest Repeated Character Substring
tags: [Leetcode, Sliding Window, Medium]

---

# 1156. Swap For Longest Repeated Character Substring
###### tags: `Leetcode` `Medium` `Sliding Window`
Link: https://leetcode.com/problems/swap-for-longest-repeated-character-substring/
## 思路
只会有两种情况：
1. 连续的好几个相同字母
2. 连续的相同字母中间有且只有一个其他字母
## Code
```java=
class Solution {
    public int maxRepOpt1(String text) {
        int[] freq = new int[26];
        List<int[]> cnt = new ArrayList<>();
        int prev = 0;
        for(int i=0;i<text.length();i++){
            freq[text.charAt(i)-'a']++;
            if(i!=0 && text.charAt(i)!=text.charAt(i-1)){
                cnt.add(new int[]{text.charAt(prev)-'a', i-prev});
                prev = i;
            }
        }
        cnt.add(new int[]{text.charAt(prev)-'a', text.length()-prev});
        
        int maxLen = 0;
        for(int i=0;i<cnt.size();i++){
            int curLen = cnt.get(i)[1];
            if(i+2<cnt.size() && cnt.get(i)[0]==cnt.get(i+2)[0] && cnt.get(i+1)[1]==1){
                curLen += cnt.get(i+2)[1];
            }
            maxLen = Math.max(maxLen, curLen+(freq[cnt.get(i)[0]]>curLen?1:0));
        }
        return maxLen;
    }
}
```