LeetCode-in-Java

3090. Maximum Length Substring With Two Occurrences

Easy

Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.

Example 1:

Input: s = “bcbbbcba”

Output: 4

Explanation:

The following substring has a length of 4 and contains at most two occurrences of each character: "bcbbbcba".

Example 2:

Input: s = “aaaa”

Output: 2

Explanation:

The following substring has a length of 2 and contains at most two occurrences of each character: "aaaa".

Constraints:

Solution

public class Solution {
    public int maximumLengthSubstring(String s) {
        int[] freq = new int[26];
        char[] chars = s.toCharArray();
        int i = 0;
        int len = s.length();
        int max = 0;
        for (int j = 0; j < len; j++) {
            ++freq[chars[j] - 'a'];
            while (freq[chars[j] - 'a'] == 3) {
                --freq[chars[i] - 'a'];
                i++;
            }
            max = Math.max(max, j - i + 1);
        }
        return max;
    }
}