fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. String s = "abcde";
  14. int k = 2;
  15.  
  16. Ans(s, k);
  17. }
  18.  
  19. public static void Ans(String s, int k) {
  20. TreeMap<Character, Integer> map = new TreeMap<>();
  21.  
  22. int left = 0;
  23. int maxLen = 0;
  24. int start = 0;
  25.  
  26. for (int right = 0; right < s.length(); right++) {
  27. char ch = s.charAt(right);
  28.  
  29. map.put(ch, map.getOrDefault(ch, 0) + 1);
  30.  
  31. while (map.lastKey() - map.firstKey() > k) {
  32. char remove = s.charAt(left);
  33.  
  34. map.put(remove, map.get(remove) - 1);
  35.  
  36. if (map.get(remove) == 0) {
  37. map.remove(remove);
  38. }
  39.  
  40. left++;
  41. }
  42.  
  43. if (right - left + 1 > maxLen) {
  44. maxLen = right - left + 1;
  45. start = left;
  46. }
  47. }
  48.  
  49. System.out.println("Substring: " +
  50. s.substring(start, start + maxLen));
  51. System.out.println("Length: " + maxLen);
  52. }
  53. }
Success #stdin #stdout 0.11s 35916KB
stdin
Standard input is empty
stdout
Substring: abc
Length: 3