Created
September 24, 2018 00:48
-
-
Save KodeSeeker/36977607b5f954087ecd4eaa313a2bee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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