#K4741. Longest Substring with At Most One Occurrence of 'a', 'b', and 'c'
Longest Substring with At Most One Occurrence of 'a', 'b', and 'c'
Longest Substring with At Most One Occurrence of 'a', 'b', and 'c'
Given a string s
consisting of lowercase English letters, determine the length of the longest contiguous substring in which each of the characters 'a', 'b', and 'c' appears at most once. In other words, in any valid substring, the count of 'a' ≤ 1, the count of 'b' ≤ 1, and the count of 'c' ≤ 1.
For example:
- For
s = "abc"
, the entire string is valid as it contains each of 'a', 'b', and 'c' exactly once. The answer is 3. - For
s = "aa"
, the valid substrings can only include a single 'a'. Hence, the answer is 1. - For
s = "abccba"
, one valid substring is "abc" (or its mirror "cba") with length 3.
You are given multiple test cases. For each test case, output the length of the longest valid substring.
The solution requires a sliding window strategy to efficiently determine the longest substring that meets the criteria.
inputFormat
The first line contains an integer T
indicating the number of test cases. Each of the next T
lines contains a single string s
.
Example:
3 abc aa abccba
outputFormat
For each test case, output a single integer on a separate line denoting the length of the longest substring of s
that contains at most one occurrence of each of the characters 'a', 'b', and 'c'.
Example:
3 1 3## sample
3
abc
aa
abccba
3
1
3
</p>