File tree Expand file tree Collapse file tree 1 file changed +18
-19
lines changed Expand file tree Collapse file tree 1 file changed +18
-19
lines changed Original file line number Diff line number Diff line change 11class Solution {
22public:
33 int lengthOfLongestSubstringTwoDistinct (string s) {
4- int current ( 0 ) ;
5- int longest ( 0 ) ;
6- int previouspos ( 0 ) ;
7- map <char , int >m;
4+ int current = 0 ;
5+ int longest = 0 ;
6+ int previouspos = 0 ;
7+ unordered_map <char , int > m;
88
9- for (int i = 0 ;i < s.length ();i++)
10- {
11- if (current < 2 && m[s[i]] == 0 ) {
12- m[s[i]] = 1 ;
9+ for (int i = 0 ; i < s.length (); i++) {
10+ m[s[i]]++;
11+ if (m[s[i]] == 1 ) {
1312 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 ;
13+ }
14+
15+ while (current > 2 ) {
16+ char ch = s[previouspos];
17+ previouspos++;
18+ m[ch]--;
19+ if (m[ch] == 0 ) {
20+ current--;
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