-
Notifications
You must be signed in to change notification settings - Fork 0
/
#13.cpp
67 lines (53 loc) · 1.34 KB
/
#13.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
60
61
62
63
64
65
66
67
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
void printMap(unordered_map<char, int> m) {
for (pair<char, int> p : m) {
cout << "{" << p.first << ", " << p.second << "}" << ", ";
}
cout << endl;
}
string largest_k_distinct(string s, int k) {
// tracks frequencies of chars in current window
unordered_map<char, int> charFreq;
charFreq[s[0]] = 1;
// left to right represents current window
int left = 0;
int right = 0;
// distinct chars in current window
int distinctChars = 1;
// longest string with k distinct chars
int maxlen = 0;
int start = 0;
while (right < s.length() - 1) {
// Moves right bound of window forward to increase distinct chars
if (distinctChars <= k) {
char newChar = s[++right];
if (charFreq.find(newChar) == charFreq.end() || charFreq[newChar] == 0) {
charFreq[newChar] = 1;
distinctChars++;
} else {
charFreq[newChar]++;
}
if (distinctChars == k && right-left+1 > maxlen) {
maxlen = right - left + 1;
start = left;
}
// Moves left bound of window forward if distinct chars > k
} else {
charFreq[s[left]]--;
if (charFreq[s[left]] == 0) distinctChars--;
left++;
}
}
return s.substr(start, maxlen);
}
int main() {
string in;
while (cin >> in) {
string s;
cin >> s;
cout << largest_k_distinct(s, stoi(in)) << endl;
}
}