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
|
class Solution { public: int k; unordered_map<char, int> heap;
void add(char c, int &x, int &y) { if (!heap[c]) x += 1; heap[c] += 1; if (heap[c] == k) y += 1; }
void del(char c, int &x, int &y) { if (heap[c] == k) y -= 1; heap[c] -= 1; if (!heap[c]) x -= 1; }
int longestSubstring(string s, int _k) { k = _k; int res = 0; for (int k = 1; k <= 26; ++k) { heap.clear(); for (int i = 0, j = 0, x = 0, y = 0; i < s.size(); ++i) { add(s[i], x, y); while (k < x) del(s[j++], x, y); if (y == x) res = max(res, i - j + 1); } } return res; } };
|