Friday, October 27, 2017

[LeetCode]Longest Substring with At Most Two Distinct Characters


Longest Substring without Repeating Character是非常类似的题目,区别只是条件稍有不同,本质的做法都是一样的。可以用sliding window解,时间复杂度O(n),空间复杂度O(n),代码如下:


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