Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Author : Saurav Kalsoor
- // K Unique String - JAVA
- import java.util.*;
- public class Test {
- static Scanner sc = new Scanner(System.in);
- public static void main(String[] args) {
- String s = sc.next();
- int k = sc.nextInt();
- System.out.println(kUniqueString(s, k));
- }
- public static int kUniqueString(String s, int k) {
- HashMap<Character, Integer> freq = new HashMap<>();
- for(int i = 0; i < s.length(); i++){
- freq.put(s.charAt(i), freq.getOrDefault(s.charAt(i), 0) + 1);
- }
- Set<MyPair> st = new TreeSet<>(new Comparator<MyPair>() {
- @Override
- public int compare(MyPair a, MyPair b) {
- if(a.frequency == b.frequency)
- return a.ch - b.ch;
- return a.frequency - b.frequency;
- }
- });
- for(Map.Entry<Character, Integer> x : freq.entrySet()){
- st.add(new MyPair(x.getKey(), x.getValue()) );
- }
- int distinct = freq.size(), changes = 0;
- for(MyPair x : st){
- if(distinct <= k)
- break;
- changes += x.frequency;
- distinct--;
- }
- return changes;
- }
- }
- class MyPair{
- public char ch;
- public int frequency;
- public MyPair(char ch, int frequency){
- this.ch = ch;
- this.frequency = frequency;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement