To solve this problem, we need to find the maximum number of distinct characters in any substring of length ( K ) from a given string ( S ). The optimal approach involves using a sliding window technique combined with a frequency array to efficiently count distinct characters as we slide the window across the string.
Approach
- Initialization: Use a frequency array of size 26 (for lowercase English letters) to keep track of character counts in the current window.
- First Window: Compute the frequency of each character in the initial window of length ( K ) and count the number of distinct characters.
- Sliding Window: For each subsequent window:
- Remove the leftmost character of the previous window and update its frequency. If its frequency becomes zero, decrease the count of distinct characters.
- Add the new rightmost character of the current window and update its frequency. If its frequency was zero before adding, increase the count of distinct characters.
- Update the maximum number of distinct characters found so far.
Solution Code
def max_distinct_substring(S, K):
n = len(S)
if K == 0 or n == 0:
return 0
if K > n:
return len(set(S)) # Only one window (entire string)
counts = [0] * 26 # For lowercase letters
# Initialize first window
for i in range(K):
char = S[i]
counts[ord(char) - ord('a')] += 1
current_distinct = sum(1 for count in counts if count > 0)
max_distinct = current_distinct
# Slide the window
for i in range(K, n):
# Remove left character from previous window
left_char = S[i - K]
left_idx = ord(left_char) - ord('a')
counts[left_idx] -= 1
if counts[left_idx] == 0:
current_distinct -= 1
# Add right character to current window
right_char = S[i]
right_idx = ord(right_char) - ord('a')
if counts[right_idx] == 0:
current_distinct += 1
counts[right_idx] += 1
# Update max distinct count
if current_distinct > max_distinct:
max_distinct = current_distinct
return max_distinct
Explanation
- Frequency Array: The frequency array allows us to quickly update and check the count of each character in constant time.
- Sliding Window: This technique ensures that we process each character exactly once, leading to an overall time complexity of ( O(N) ) (where ( N ) is the length of the string).
- Space Complexity: The space complexity is ( O(1) ) since the frequency array size is fixed (26 elements).
This approach efficiently finds the maximum number of distinct characters in any substring of length ( K ) and handles all edge cases (like ( K ) being larger than the string length or ( K = 1 )).
Example: For ( S = "abcabc" ) and ( K = 3 ), the maximum distinct characters in any substring of length 3 is 3 (e.g., "abc").
Another Example: For ( S = "aabacbebebe" ) and ( K =3 ), the maximum distinct characters is 3 (e.g., "bac", "acb", etc.).
This solution is optimal and works well for large input sizes.


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