Last active
January 10, 2018 06:14
-
-
Save sourabh2k15/3cf06904b0c849e7598e7e6efcbb524e to your computer and use it in GitHub Desktop.
159. Longest Substring with At Most Two Distinct Characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| int lengthOfLongestSubstringTwoDistinct(string s) { | |
| if(s.length() == 0) return 0; | |
| unordered_map<char, int> table; | |
| int begin = 0, end = 0, len = 0, counter = 0; | |
| while(end < s.length()){ | |
| char current = s[end]; | |
| table[current]++; | |
| if(table[current] == 1) counter++; | |
| end++; | |
| while(counter > 2){ | |
| char startchar = s[begin]; | |
| if(table.count(startchar) == 1){ | |
| table[startchar]--; | |
| if(table[startchar] == 0) counter--; | |
| } | |
| begin++; | |
| } | |
| len = max(len, end - begin); | |
| } | |
| return len; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment