forked from imnishant/GeeksforGeeks-Java-Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest-K-Unique-Character
38 lines (35 loc) · 959 Bytes
/
Longest-K-Unique-Character
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args) throws Exception
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine().trim());
while(t-- > 0)
{
char ch[] = bf.readLine().trim().toCharArray();
int k = Integer.parseInt(bf.readLine().trim());
int map[] = new int[26];
int max = 0, j = 0, count = 0;
for(int i=0 ; i<ch.length ; i++)
{
if(map[ch[i] - 'a']++ == 0)
count++;
if(count > k)
{
while(--map[ch[j++] - 'a'] > 0);
count--;
}
if(count == k)
{
max = Math.max(max, i - j + 1);
}
}
if(count != k)
max = -1;
System.out.println(max);
}
}
}