码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Longest Substring with At Most Two Distinct Characters

时间:2015-03-20 08:06:07      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

At first beginning, I was trying to use hash set to record the characters. But I found that was wrong.

Because if there are couple same chars, when you erase it, you lost all the information and cause the result wrong.

 

Note:

size > 2 not size > 1

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int len = s.size(), result = 0;
        if (len < 2) return len;
        unordered_map<char, int> mapping;
        for (int left = 0, right = 0; right < len; right++) {
            if (mapping.find(s[right]) != mapping.end()) {
                mapping[s[right]]++;
            } else {
                mapping[s[right]] = 1;
                while (mapping.size() > 2) {
                    char tmp = s[left++];
                    if (mapping[tmp] > 1) mapping[tmp]--;
                    else mapping.erase(tmp);
                }
            }
            result = max(result, right - left + 1);
        }
        return result;
    }
};

 

LeetCode – Refresh – Longest Substring with At Most Two Distinct Characters

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4352700.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!