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. // store unique char in set
  14. String s = "pqpqs";
  15. int k = 2;
  16. int n = s.length();
  17. Set<Character> set = new HashSet<>();
  18. long count = 0;
  19. HashMap<Character, Integer> mp =new HashMap<>();
  20. for(int i=0, j=0; j<n; j++){
  21. mp.put(s.charAt(j), mp.getOrDefault(s.charAt(j), 0) +1);
  22. // reduce wndow of pointer if count>k
  23. while(mp.size() > k){
  24. mp.put(s.charAt(i), mp.getOrDefault(s.charAt(i), 0) - 1);
  25. if(mp.get(s.charAt(i))==0){
  26. mp.remove(s.charAt(i)); // if freq 0 then remove it
  27. }
  28. i++; // move pointer toward right
  29. }
  30. // all subarrays ending at j are valid
  31. count+=(j - i+1);
  32. }
  33. System.out.print(count);
  34. }
  35. }
Success #stdin #stdout 0.1s 54580KB
stdin
Standard input is empty
stdout
12