Longest Substring with At most 2 Distinct Characters

/**
Longest Substring with At Most Two Distinct Characters
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.
*/
import java.util.*;
public class LongestSubstringWithAtmost2DistinctChars{

public static int lengthOfLongestSubstring(String s){
int res = 0, left = 0;
HashMap<Character, Integer> map = new HashMap<>();
for(int i=0;i<s.length(); i++){
char c = s.charAt(i);
map.put(c, map.getOrDefault(c, 0) +1);
while(map.size()>2){
char l = s.charAt(left);
map.put(l, map.get(l)-1);
if(map.get(l)==0){
map.remove(l);
}
left++;
}
res = Math.max(res, i-left+1);
}
return res;
}

public static void main(String[] args){
System.out.println(lengthOfLongestSubstring("eceba"));
}

}

No comments:

Post a Comment