-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest Subarray with K Unique characters.java
49 lines (46 loc) · 1.21 KB
/
Longest Subarray with K Unique characters.java
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
39
40
41
42
43
44
45
46
47
48
49
import java.util.*;
public class Solution {
public static void main(String[] args) {
int arr = longestSubstringWithKUniqueCharacters("aabacbebe", 3);
System.out.print(arr);
}
public static int longestSubstringWithKUniqueCharacters(String s, int k) {
// Write your code here.
int max =0;
int[] table = new int[26];
int start=0,end=0;
while(end < s.length())
{
table[s.charAt(end) - 'a']++;
if(mapSize(table) == k)
{
max = Math.max(max, end - start + 1);
System.out.println(max + " end: " + end + " start: " + start);
}
if(mapSize(table) > k)
{
while(mapSize(table) > k)table[s.charAt(start++)-'a']--;
}
end++;
}
return max;
}
public static int mapCount(int[] arr)
{
int res =0;
for(int i=0;i<arr.length;i++)
{
res += arr[i];
}
return res;
}
public static int mapSize(int[] arr)
{
int size =0;
for(int i=0;i<arr.length;i++)
{
if(arr[i] != 0)size++;
}
return size;
}
}