#K7626. Longest Substring with At Most Two Distinct Characters

    ID: 34603 Type: Default 1000ms 256MiB

Longest Substring with At Most Two Distinct Characters

Longest Substring with At Most Two Distinct Characters

Given a string s, find the length of the longest substring that contains at most two distinct characters.

The substring is a contiguous sequence of characters within the string. Your task is to compute its length such that there are at most two unique characters in that substring.

For example:

  • For s = "eceba", the longest substring is "ece" which has a length of 3.
  • For s = "abc", the longest substring might be "ab" or "bc" with a length of 2.

Note: If the string length is less than 3, then the answer is the length of the string.

The solution uses a sliding window approach to maintain the current substring and adjusts it when more than two distinct characters are present. The window size at any point is calculated as \( right - left + 1 \), where left and right denote the window boundaries.

inputFormat

The input consists of a single line containing the string s.

Input Format: A string read from standard input (stdin).

outputFormat

Output a single integer representing the length of the longest substring with at most two distinct characters.

Output Format: The integer should be printed to standard output (stdout).

## sample
eceba
3