题目:
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example,Given s = “eceba”
,
T is "ece" which its length is 3.
题解:HashMap保存两个字母的映射,双指针start, end。
C++版:
class Solution { public: int lengthOfLongestSubstringTwoDistinct(string s) { if(s.length() <= 2) return s.length(); int start = 0, end = 0; unordered_map<char, int> d; int maxL = 0; d.insert(pair<char, int>(s[start], 1)); while(end < s.length() - 1) { int l = end - start + 1; while(d.size() <= 2 && end < s.length() - 1) { if(d.size() == 2 && d.find(s[end + 1]) == d.end()) break; end++; if(d.find(s[end]) != d.end()) d[s[end]]++; else d.insert(pair<char, int>(s[end], 1)); l++; } if(l > maxL) maxL = l; if(d[s[start]] > 1) d[s[start]]--; else d.erase(s[start]); start++; } return maxL; } };
import java.util.Hashtable; public class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { if(s.length() <= 2) return s.length(); int start = 0, end = 0, maxL = 0; Hashtable<Character, Integer> d = new Hashtable<>(); d.put(s.charAt(0), 1); while(end < s.length() - 1) { int l = end - start + 1; while(end < s.length() - 1 && d.size() <= 2) { if(d.size() == 2 && !d.containsKey(s.charAt(end + 1))) break; end++; if(d.containsKey(s.charAt(end))) d.put(s.charAt(end), d.get(s.charAt(end)) + 1); else d.put(s.charAt(end), 1); l++; } if(l > maxL) maxL = l; if(d.get(s.charAt(start)) > 1) d.put(s.charAt(start), d.get(s.charAt(start)) - 1); else d.remove(s.charAt(start)); start++; } return maxL; } }
class Solution(object): def lengthOfLongestSubstringTwoDistinct(self, s): """ :type s: str :rtype: int """ if len(s) <= 2: return len(s) maxL = 0 start, end = 0, 0 d = {} d[s[start]] = 1 while end < len(s) - 1: l = end - start + 1 while len(d) <= 2 and end < len(s) - 1: temp = end + 1 if s[temp] not in d and len(d) == 2: break end += 1 if s[end] in d: d[s[end]] += 1 else: d[s[end]] = 1 l += 1 if l > maxL: maxL = l if d[s[start]] > 1: d[s[start]] -= 1 else: del d[s[start]] start += 1 return maxL