Advertisement
Kali_prasad

valid substring with no char pairs difference greater than k

Dec 18th, 2024
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. import java.util.*;
  2. // Online Java Compiler
  3. // Use this editor to write, compile and run your Java code online
  4.  
  5. /*
  6. test case -
  7.  
  8. abccadfdd
  9. 3
  10.  
  11. expected ans -
  12. abccad
  13. */
  14.  
  15. public class Main {
  16.  
  17.   public static boolean checkIfValidSubString(int k,LinkedHashSet<Character>  charSet){
  18.     int difference = Math.abs(Collections.max(charSet) - Collections.min(charSet));
  19.     return difference<=k;
  20.   }
  21.   public static String getMaxValidSubString(String s,int k){
  22.     int left =0,right = 0;
  23.     int mainLeft =0,mainRight = 0;
  24.  
  25.     HashMap<Character, Integer> frequencyMap = new HashMap<>();
  26.     LinkedHashSet<Character> charSet = new LinkedHashSet<>();
  27.  
  28.     while(left<=right && right<s.length()){
  29.       char currChar = s.charAt(right);
  30.       int currCharFreq = frequencyMap.getOrDefault(currChar, 0);
  31.       if(currCharFreq==0) {
  32.         frequencyMap.put(currChar,1);
  33.       }else{
  34.         frequencyMap.put(currChar,currCharFreq+1);
  35.       }
  36.       charSet.add(currChar);
  37.       while(left<=right && !checkIfValidSubString(k,charSet) ){
  38.         char leftChar = s.charAt(left);
  39.         int leftCharFreq = frequencyMap.get(leftChar);
  40.         if(leftCharFreq<=1){
  41.           charSet.remove(leftChar);
  42.         }
  43.         frequencyMap.put(leftChar,leftCharFreq-1);
  44.         left+=1;
  45.       }
  46.  
  47.       if(left<s.length() && ((mainRight-mainLeft)<(right-left))){
  48.         mainRight = right;
  49.         mainLeft = left;
  50.       }
  51.       right+=1;
  52.     }
  53.    
  54.     return s.substring(mainLeft,mainRight+1);
  55.   }
  56.   public static void main(String[] args) {
  57.       Scanner sc = new Scanner(System.in);
  58.       String s = sc.nextLine();
  59.       int k = sc.nextInt();
  60.       System.out.println(getMaxValidSubString(s,k));
  61.   }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement