Skip to content

Instantly share code, notes, and snippets.

@KodeSeeker
Created September 24, 2018 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KodeSeeker/36977607b5f954087ecd4eaa313a2bee to your computer and use it in GitHub Desktop.
Save KodeSeeker/36977607b5f954087ecd4eaa313a2bee to your computer and use it in GitHub Desktop.
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ans" +lengthOfLongestSubstringTwoDistinct("eceba") );
System.out.println("Ans" +lengthOfLongestSubstringTwoDistinct("ecebaba") );
}
static int lengthOfLongestSubstringTwoDistinct(String s) {
int end = 0, begin = 0;
Map<Character, Integer> map = new HashMap<>();
int maxLen = 0;
int counter = 0;
while(end < s.length()) {
char curr = s.charAt(end);
if(!map.containsKey(curr)) {
map.put(curr,1);
counter++;
} else {
map.put(curr,map.get(curr)+1);
}
end++;
while(counter > 2) {
char bChar = s.charAt(begin);
map.put(bChar, map.get(bChar) -1);
begin++;
if(map.get(bChar) == 0){
counter--;
}
}
if(end - begin > maxLen) {
maxLen = end -begin;
System.out.println(s.substring(begin,end));
}
}
return maxLen;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment