Longest substring with at most k different characters

Published on Nov 29, 2016 • Ruslan Ledesma-Garza

For a given string, find the length of the longest substring that contains at most k different characters.

For example, for string “abacd” and at most 2 characters, the longest
substring is “aba” and thus the answer is 3.

Your task is to write a method longest that takes an integer k and a string
and gives the longest substring that contains at most k different
characters.

Input and output.
The signature of the method is longest(k, s), where k is an integer
and s is a string. The return value is an integer.