#C12138. Longest Substring with At Most Two Distinct Characters
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 contiguous substring that contains at most two distinct characters. In other words, for a substring s[i...j], it must satisfy that the number of unique characters in it is at most 2. Formally, if we denote by \(\#distinct(s[i...j])\) the number of distinct characters in the substring, then we require:
[ #distinct(s[i...j]) \le 2 ]
Your task is to compute the maximum \(j-i+1\) among all valid substrings. For example, if s = "eceba"
, one of the longest valid substrings is "ece" with a length of 3.
inputFormat
The input consists of a single line containing the string s
.
You should read the input from stdin.
outputFormat
Output a single integer which is the length of the longest substring of s
that contains at most two distinct characters. Write the output to stdout.
eceba
3