File tree Expand file tree Collapse file tree 1 file changed +19
-20
lines changed Expand file tree Collapse file tree 1 file changed +19
-20
lines changed Original file line number Diff line number Diff line change 11class Solution {
22public:
33 int lengthOfLongestSubstringKDistinct (string s, int k) {
4- int current (0 );
5- int longest (0 );
6- int previouspos (0 );
7- map<char , int >m;
4+ int longest = 0 ;
5+ int previouspos = 0 ;
6+ unordered_map<char , int >m;
87
9- for (int i = 0 ;i < s.length ();i++)
10- {
11- if (current < k && m[s[i]] == 0 ) {
12- m[s[i]] = 1 ;
13- current++;
14- } else if (m[s[i]] > 0 ) {
15- m[s[i]]++;
16- } else {
17- longest = max (longest, i-previouspos);
18- m[s[i]] = 1 ;
19- while (true ) {
20- char ch = s[previouspos];
21- previouspos++;
22- m[ch]--;
23- if (m[ch] == 0 ) break ;
8+ int cnt = 0 ;
9+ for (int i = 0 ; i < s.length (); i++) {
10+ m[s[i]]++;
11+ if (m[s[i]] == 1 ) {
12+ cnt++;
13+ }
14+
15+ while (cnt > k) {
16+ char ch = s[previouspos];
17+ previouspos++;
18+ m[ch]--;
19+ if (m[ch] == 0 ) {
20+ cnt--;
2421 }
2522 }
23+
24+ longest = max (longest, i-previouspos+1 );
2625 }
27- longest = max (longest, ( int )s. length ()-previouspos);
26+
2827 return longest;
2928 }
3029};
You can’t perform that action at this time.
0 commit comments