内容中心

2026年质量好的泡沫箱批量采购厂家推荐-昆明官宝泡沫有限公司

To solve this problem, we need to find the length of the longest substring in a given string that contains at most two distinct characters. This is a classic sliding window problem where we maintain a window of characters and adjust its size to ensure it only contains up to two distinct characters.

Approach

The sliding window technique involves using two pointers (left and right) to represent the current window of characters. We also use a frequency dictionary to keep track of the count of each character in the window. Here's the step-by-step approach:

  1. Initialize:

    • left pointer at the start of the string.
    • max_len to store the length of the longest valid substring.
    • A frequency dictionary to count occurrences of characters in the current window.
  2. Expand the window:

    • Move the right pointer to include the next character in the window.
    • Update the frequency of the current character.
  3. Shrink the window:

    • If the number of distinct characters in the window exceeds two, move the left pointer to the right until the window has at most two distinct characters.
    • Adjust the frequency dictionary as characters are removed from the window (remove the character from the dictionary if its count becomes zero).
  4. Update maximum length:

    • After each valid window adjustment, check if the current window length is the longest encountered so far and update max_len accordingly.

Solution Code

from collections import defaultdict

def lengthOfLongestSubstringTwoDistinct(s):
    freq = defaultdict(int)
    left = 0
    max_len = 0

    for right in range(len(s)):
        char = s[right]
        freq[char] += 1

        # Shrink the window if more than two distinct characters
        while len(freq) > 2:
            left_char = s[left]
            freq[left_char] -= 1
            if freq[left_char] == 0:
                del freq[left_char]
            left += 1

        # Update the maximum length
        current_len = right - left + 1
        if current_len > max_len:
            max_len = current_len

    return max_len

Explanation

  • Time Complexity: O(n) where n is the length of the string. Each character is added to the window once and removed once, so the total number of operations is linear.
  • Space Complexity: O(1) because the frequency dictionary can hold at most three entries (since we only allow up to two distinct characters in the window at any time).

This approach efficiently finds the longest substring with at most two distinct characters by maintaining a sliding window and adjusting it dynamically based on the number of distinct characters present.

Answer: The function lengthOfLongestSubstringTwoDistinct returns the length of the longest substring with at most two distinct characters. For example, if the input is "eceba", the output is 3. If the input is "ccaabbb", the output is 5.

The final answer is the code provided above.

from collections import defaultdict

def lengthOfLongestSubstringTwoDistinct(s):
    freq = defaultdict(int)
    left = 0
    max_len = 0

    for right in range(len(s)):
        char = s[right]
        freq[char] += 1

        while len(freq) > 2:
            left_char = s[left]
            freq[left_char] -= 1
            if freq[left_char] == 0:
                del freq[left_char]
            left += 1

        current_len = right - left + 1
        if current_len > max_len:
            max_len = current_len

    return max_len

昆明官宝泡沫有限公司

昆明官宝泡沫有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?