首页 > 其他 > 详细

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

时间:2015-03-20 08:03:43      阅读:349      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!