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
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] Longest Substring with At Most Two Distinct Characters及扩展
- Leetcode 159 & 340 Longest Substring with At Most Two/K Distinct Characters
- [LeetCode] Longest Substring with At Most Two Distinct Characters
- [leetcode]Longest Substring with At Most Two Distinct Characters
- Leetcode: Longest Substring with At Most Two Distinct Characters
- Leetcode-Longest Substring with At Most Two Distinct Characters.
- [LeetCode] Longest Substring with At Most Two Distinct Characters
- LeetCode - Longest Substring with At Most Two Distinct Characters
- leetcode[159]Longest Substring with At Most Two Distinct Characters
- [Leetcode] Longest Substring with At Most Two Distinct Characters
- Leetcode 159 Longest Substring with At Most Two Distinct Characters
- LeetCode Longest Substring with At Most Two Distinct Characters
- 【LeetCode】Longest Substring with At Most Two Distinct Characters (2 solutions)
- Leetcode: Longest Substring with At Most Two Distinct Characters
- [Leetcode]Longest Substring with At Most Two Distinct Characters
- leetcode 159: Longest Substring with At Most Two Distinct Characters
- [LeetCode160]Longest Substring with At Most Two Distinct Characters
- [leetcode] 159. Longest Substring with At Most Two Distinct Characters 解题报告
- LeetCode "Longest Substring with At Most Two Distinct Characters"
- Leetcode 159 Longest Substring with At Most Two Distinct Characters