Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- // Online Java Compiler
- // Use this editor to write, compile and run your Java code online
- /*
- test case -
- abccadfdd
- 3
- expected ans -
- abccad
- */
- public class Main {
- public static boolean checkIfValidSubString(int k,LinkedHashSet<Character> charSet){
- int difference = Math.abs(Collections.max(charSet) - Collections.min(charSet));
- return difference<=k;
- }
- public static String getMaxValidSubString(String s,int k){
- int left =0,right = 0;
- int mainLeft =0,mainRight = 0;
- HashMap<Character, Integer> frequencyMap = new HashMap<>();
- LinkedHashSet<Character> charSet = new LinkedHashSet<>();
- while(left<=right && right<s.length()){
- char currChar = s.charAt(right);
- int currCharFreq = frequencyMap.getOrDefault(currChar, 0);
- if(currCharFreq==0) {
- frequencyMap.put(currChar,1);
- }else{
- frequencyMap.put(currChar,currCharFreq+1);
- }
- charSet.add(currChar);
- while(left<=right && !checkIfValidSubString(k,charSet) ){
- char leftChar = s.charAt(left);
- int leftCharFreq = frequencyMap.get(leftChar);
- if(leftCharFreq<=1){
- charSet.remove(leftChar);
- }
- frequencyMap.put(leftChar,leftCharFreq-1);
- left+=1;
- }
- if(left<s.length() && ((mainRight-mainLeft)<(right-left))){
- mainRight = right;
- mainLeft = left;
- }
- right+=1;
- }
- return s.substring(mainLeft,mainRight+1);
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- String s = sc.nextLine();
- int k = sc.nextInt();
- System.out.println(getMaxValidSubString(s,k));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement