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;
    }
};

 

posted on 2015-03-20 07:52  keepshuatishuati  阅读(128)  评论(0编辑  收藏  举报