/*
using hashset store at most 2 unique characters, however it is not easy to extend to k characters
using hashmap to store the last occurrence of each character coped with finding left most the character with the left most index
*/
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) return 0;
int start = 0;
int end = 0;
int res = 0;
//char[] dict = new char[2];
//HashSet<Character> dict = new HashSet<Character>();
HashMap<Character, Integer> dict = new HashMap<Character, Integer>();
while( end < s.length()){
if (dict.size() <= 2){
dict.put(s.charAt(end), end);
end++;
}
if (dict.size() > 2) {
int leftMost = s.length();
for(int i : dict.values()){
leftMost = Math.min(leftMost, i);
}
dict.remove(s.charAt(leftMost));
start = leftMost + 1;
}
res = Math.max(res, end - start);
}
return res;
}
}