1156. 单字符重复子串的最大长度

发布时间 2023-06-07 09:58:15作者: Tianyiya

如果字符串中的所有字符都相同,那么这个字符串是单字符重复的字符串。

给你一个字符串 text,你只能交换其中两个字符一次或者什么都不做,然后得到一些单字符重复的子串。返回其中最长的子串的长度。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/swap-for-longest-repeated-character-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int maxRepOpt1(String text) {
        if (text == null || text.length() == 0) {
            return 0;
        }
        int ans = 0;
        int[] count = new int[256];
        for (int i = 0; i < text.length(); i++) {
            count[text.charAt(i)]++;
        }
        for (int i = 0; i < text.length(); ) {
            int j = i;
            while (j < text.length() && text.charAt(i) == text.charAt(j)) {
                j++;
            }
            if ((j - i) < count[text.charAt(i)] && (i > 0 || j < text.length())) {
                ans = Math.max(ans, j - i + 1);
            }
            int k = j + 1;
            while (k < text.length() && text.charAt(k) == text.charAt(i)) {
                k++;
            }
            ans = Math.max(ans, Math.min(k - i, count[text.charAt(i)]));
            i = j;
        }

        return ans;
    }
}