import java.util.*; import java.io.*; public class Main { public static int lengthOfLongestSubstringTwoDistinct(String s) { HashMap<Character,Integer> map = new HashMap<>(); int distinct= 0; int start =0; int ans = 0; for(int i = 0 ; i < s.length();i++){ char ch = s.charAt(i); if(map.containsKey(ch)==false) distinct++; map.put(ch , map.getOrDefault(ch,0)+1); while(distinct>2){ char temp = s.charAt(start); if(map.get(temp)==1){ map.remove(temp); distinct--; } else{ map.put(temp , map.get(temp)-1); } start++; } ans = Math.max(ans , i - start+1); } return ans; } public static void main(String[] args) throws java.lang.Exception { Scanner scn = new Scanner(System.in); int ans = lengthOfLongestSubstringTwoDistinct(scn.nextLine()); System.out.println(ans); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter