[LeetCode] 3090. Maximum Length Substring With Two Occurrences

CNoodle發表於2024-11-10

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:
2 <= s.length <= 100
s consists only of lowercase English letters.

每個字元最多出現兩次的最長子字串。

給你一個字串 s ,請找出滿足每個字元最多出現兩次的最長子字串,並返回該子字串的 最大 長度。

思路

這道題不難看出是用滑動視窗的思路,而且這道題很像159題。這道題左指標的移動條件是隻要某個字母的出現次數大於2,就移動左指標。其餘思路同一般滑動視窗題。

複雜度

時間O(n)
空間O(1)

程式碼

Java實現

class Solution {
    public int maximumLengthSubstring(String s) {
        int start = 0;
        int end = 0;
        int[] map = new int[256];
        int res = 0;
        while (end < s.length()) {
            char c1 = s.charAt(end);
            end++;
            map[c1]++;
            // 如果某個字母的出現次數大於2,就移動左指標
            while (map[c1] > 2) {
                char c2 = s.charAt(start);
                start++;
                map[c2]--;
            }
            res = Math.max(res, end - start);
        }
        return res;
    }
}

相關文章