Skip to content

Commit 119144a

Browse files
authored
159. Longest Substring with At Most Two Distinct Characters
1 parent ef24515 commit 119144a

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed
Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,29 @@
11
class Solution {
22
public:
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
};

0 commit comments

Comments
 (0)