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.
思路:
遍歷字符串痒筒,用哈希表存儲遍歷到的字符當(dāng)前最右的位置蹂匹。
如果哈希表大小大于2柴梆,證明當(dāng)前有3個(gè)不同的字符,需要去掉一個(gè)蜡娶,把位置最靠左的去掉沃饶,就能夠算出到當(dāng)前字符為止先紫,最長的len是多大。
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) {
return 0;
}
Map<Character, Integer> map = new HashMap<>();
int res = 0;
int left = -1;
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), i);
if (map.size() > 2) {
int leftest = s.length();
for (Character c : map.keySet()) {
leftest = Math.min(leftest, map.get(c));
}
left = leftest;
map.remove(s.charAt(leftest));
}
res = Math.max(res, i - left);
}
return res;
}