Thursday, June 1, 2017

Longest sub-string with N unique characters

The program must find the length L of the longest sub-string with N unique characters in a given string value S 

Input Format:

The first line will contain the string value S.
The second line will contain the number of unique characters N.

Output Format:

Length L of the sub-string longest sub-string with N unique characters.

Example Input/Output 1: 

Input:
abcdcdabcdef
2

Output:
4

Explanation:
The longest possible substring with 2 unique characters in abcdcdabcdef is cdcd whose length is 4.

Solution:

s = input()
n = int(input())
a = []
for i in range(len(s)):
    for j in range(1,len(s)+1):
        st = s[i:j]
        y = set(st)
        if len(y) == n:
            if len(a) < len(st):
                a = st

print(len(a))
Share: