Advertisement
saurav_kalsoor

K Unique String - JAVA

Jul 18th, 2022
1,103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Author : Saurav Kalsoor
  2. // K Unique String - JAVA
  3.  
  4. import java.util.*;
  5.  
  6. public class Test {
  7.     static Scanner sc = new Scanner(System.in);
  8.     public static void main(String[] args) {
  9.         String s = sc.next();
  10.         int k = sc.nextInt();
  11.  
  12.         System.out.println(kUniqueString(s, k));
  13.     }
  14.  
  15.     public static int kUniqueString(String s, int k) {
  16.         HashMap<Character, Integer> freq = new HashMap<>();
  17.  
  18.         for(int i = 0; i < s.length(); i++){
  19.             freq.put(s.charAt(i), freq.getOrDefault(s.charAt(i), 0) + 1);
  20.         }
  21.  
  22.         Set<MyPair> st = new TreeSet<>(new Comparator<MyPair>() {
  23.             @Override
  24.             public int compare(MyPair a, MyPair b) {
  25.                 if(a.frequency == b.frequency)
  26.                     return a.ch - b.ch;
  27.                 return a.frequency - b.frequency;
  28.             }
  29.         });
  30.  
  31.         for(Map.Entry<Character, Integer> x : freq.entrySet()){
  32.             st.add(new MyPair(x.getKey(), x.getValue()) );
  33.         }
  34.  
  35.         int distinct = freq.size(), changes = 0;
  36.  
  37.         for(MyPair x : st){
  38.             if(distinct <= k)
  39.                 break;
  40.  
  41.             changes += x.frequency;
  42.             distinct--;
  43.         }
  44.  
  45.         return changes;
  46.     }
  47.    
  48. }
  49.  
  50. class MyPair{
  51.     public char ch;
  52.     public int frequency;
  53.  
  54.     public MyPair(char ch, int frequency){
  55.         this.ch = ch;
  56.         this.frequency = frequency;
  57.     }
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement