您的位置:首页 > 其它

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

2015-03-20 07:52 393 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: