forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest_substring_with_exactly_k_distinct_characters.cpp
59 lines (43 loc) · 1.41 KB
/
longest_substring_with_exactly_k_distinct_characters.cpp
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
50
51
52
53
54
55
56
57
58
59
/*
Given a string you need to print the size of the longest possible substring that has exactly K unique characters. If there is no possible substring then print -1.
Example 1:
Input:
S = "aabacbebebe", K = 3
Output: 7
Explanation: "cbebebe" is the longest
substring with K distinct characters.
Example 2:
Input:
S = "aaaa", K = 2
Output: -1
Explanation: There's no substring with K
distinct characters.
Your Task:
You don't need to read input or print anything. Your task is to complete the function longestKSubstr() which takes the string S and an integer K as input and returns the length of the longest substring with exactly K distinct characters. If there is no substring with exactly K distinct characters then return -1.
Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).
Constraints:
1<=|S|<=105
1<=K<=105
*/
class Solution{
public:
int longestKSubstr(string s, int k) {
int start = 0, end = 0, n = s.length(), res = 0;
unordered_map <char, int> m;
while (end < n) {
m[s[end]]++;
if (m.size() == k) {
res = max(res, end - start + 1);
}
if (m.size() > k) {
m[s[start]]--;
if (m[s[start]] == 0) m.erase(s[start]);
start++;
}
end++;
}
if (res == 0) return -1;
else return res;
}
};