和Longest Substring without Repeating Character是非常类似的题目,区别只是条件稍有不同,本质的做法都是一样的。可以用sliding window解,时间复杂度O(n),空间复杂度O(n),代码如下:
This file contains 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) { | |
int len = s.size(), left = 0, maxLen = 0; | |
unordered_map<char, int> map; | |
for(int i = 0; i < len; ++i) | |
{ | |
++map[s[i]]; | |
while(map.size() > 2) | |
{ | |
char c = s[left++]; | |
--map[c]; | |
if(!map[c])map.erase(c); | |
} | |
maxLen = max(maxLen, i - left + 1); | |
} | |
return maxLen; | |
} | |
}; |
No comments:
Post a Comment