#K13561. Longest Substring with At Most K Distinct Characters

    ID: 23940 Type: Default 1000ms 256MiB

Longest Substring with At Most K Distinct Characters

Longest Substring with At Most K Distinct Characters

Given a string s and an integer k, your task is to find the length of the longest substring of s that contains at most k distinct characters. This problem is a typical sliding window problem which requires you to dynamically adjust the window to ensure that the condition is met.

Examples:

  • Input: s = "eceba", k = 2     Output: 3
  • Input: s = "abcde", k = 1     Output: 1

Note: If k is zero, or if the string is empty, the result should be 0.

inputFormat

The input is read from standard input and consists of two lines:

  1. The first line contains a non-empty string s.
  2. The second line contains an integer k representing the maximum number of distinct characters allowed in the substring.

outputFormat

Output a single integer representing the length of the longest substring of s that contains at most k distinct characters. The output should be printed to standard output.

## sample
eceba
2
3