Q60 PepCoding | Longest Substring With At Most Two Distinct Characters
Sat Feb 04 2023 06:04:23 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
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);
}
}
content_copyCOPY
https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/longest-substring-with-at-most-two-distinct-characters/ojquestion
Comments