SHOW:
|
|
- or go back to the newest paste.
| 1 | // Author : Saurav Kalsoor | |
| 2 | - | // K Unique String - JAVA |
| 2 | + | // K Unique String - KOTLIN |
| 3 | ||
| 4 | import java.util.*; | |
| 5 | ||
| 6 | - | public class Test {
|
| 6 | + | var sc = Scanner(System.`in`) |
| 7 | - | static Scanner sc = new Scanner(System.in); |
| 7 | + | |
| 8 | - | public static void main(String[] args) {
|
| 8 | + | fun main() {
|
| 9 | - | String s = sc.next(); |
| 9 | + | val s = sc.next() |
| 10 | - | int k = sc.nextInt(); |
| 10 | + | val k = sc.nextInt() |
| 11 | println(kUniqueString(s, k)) | |
| 12 | - | System.out.println(kUniqueString(s, k)); |
| 12 | + | |
| 13 | ||
| 14 | fun kUniqueString(s: String, k: Int): Int {
| |
| 15 | - | public static int kUniqueString(String s, int k) {
|
| 15 | + | val freq = HashMap<Char, Int>() |
| 16 | - | HashMap<Character, Integer> freq = new HashMap<>(); |
| 16 | + | for (i in 0 until s.length) {
|
| 17 | freq[s[i]] = freq.getOrDefault(s[i], 0) + 1 | |
| 18 | - | for(int i = 0; i < s.length(); i++){
|
| 18 | + | |
| 19 | - | freq.put(s.charAt(i), freq.getOrDefault(s.charAt(i), 0) + 1); |
| 19 | + | val st: MutableSet<MyPair> = |
| 20 | - | } |
| 20 | + | TreeSet { a, b ->
|
| 21 | if (a.frequency == b.frequency) | |
| 22 | - | Set<MyPair> st = new TreeSet<>(new Comparator<MyPair>() {
|
| 22 | + | a.ch - b.ch |
| 23 | - | @Override |
| 23 | + | else |
| 24 | - | public int compare(MyPair a, MyPair b) {
|
| 24 | + | a.frequency - b.frequency |
| 25 | - | if(a.frequency == b.frequency) |
| 25 | + | } |
| 26 | - | return a.ch - b.ch; |
| 26 | + | |
| 27 | - | return a.frequency - b.frequency; |
| 27 | + | for ((key, value) in freq) {
|
| 28 | - | } |
| 28 | + | st.add(MyPair(key, value)) |
| 29 | - | }); |
| 29 | + | |
| 30 | var distinct = freq.size | |
| 31 | - | for(Map.Entry<Character, Integer> x : freq.entrySet()){
|
| 31 | + | var changes = 0 |
| 32 | - | st.add(new MyPair(x.getKey(), x.getValue()) ); |
| 32 | + | for (x in st) {
|
| 33 | - | } |
| 33 | + | if (distinct <= k) break |
| 34 | changes += x.frequency | |
| 35 | - | int distinct = freq.size(), changes = 0; |
| 35 | + | distinct-- |
| 36 | } | |
| 37 | - | for(MyPair x : st){
|
| 37 | + | return changes |
| 38 | - | if(distinct <= k) |
| 38 | + | |
| 39 | - | break; |
| 39 | + | |
| 40 | internal class MyPair(var ch: Char, var frequency: Int) |