leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0395.cpp (981B)
0 class Solution {
1 public:
2 int longestSubstring(const string &s, int k) const {
3 const int n = size(s);
4 static int count[26];
5 int res = 0, maxUnique = 0;
7 memset(count, 0x00, sizeof(count));
8 for (const char c : s)
9 maxUnique += !count[c - 'a']++;
11 for (int l = 1; l <= maxUnique; l++) {
12 memset(count, 0x00, sizeof(count));
13 int i = 0, j = 0, unique = 0, least = 0;
14 while (j < n) {
15 if (unique <= l) {
16 unique += !count[s[j] - 'a']++;
17 least += count[s[j] - 'a'] == k;
18 j++;
19 } else {
20 least -= count[s[i] - 'a'] == k;
21 unique -= !--count[s[i] - 'a'];
22 i++;
23 }
25 if (unique == l && least == l) {
26 res = max(res, j - i);
27 }
28 }
29 }
31 return res;
32 }
33 };