Loading problem...
You are provided with a string s composed of English letters (both uppercase and lowercase). Your objective is to determine the length of the longest contiguous segment (substring) within the string that contains no more than two different characters.
A substring is a continuous sequence of characters within the original string. The constraint here is on character diversity—the segment you identify must use at most two unique character types, though each character may appear any number of times within that segment.
Your task is to analyze the string and return the maximum possible length of such a valid segment. If the entire string qualifies (contains at most two distinct characters), return its full length.
s = "eceba"3The segment "ece" contains only the characters 'e' and 'c', satisfying the two-character limit. Its length is 3, which is the maximum achievable for this input.
s = "ccaabbb"5The segment "aabbb" contains only 'a' and 'b'. With length 5, it is the longest valid segment in the string.
s = "ababab"6The entire string "ababab" contains only two distinct characters ('a' and 'b'), so the full length of 6 is returned.
Constraints