[Leetcode]3085.Minimum Deletions to Make String K-Special

294 阅读2分钟

Description:
You are given a string word and an integer k.

We consider word to be k-special if |freq(word[i]) - freq(word[j])| <= k for all indices i and j in the string.

Here, freq(x) denotes the 

frequency

 of the character x in word, and |y| denotes the absolute value of y.

Return the minimum number of characters you need to delete to make word k-special.

Example 1:

Input: word = "aabcaba", k = 0
Output: 3
Explanation:  We can make `word` `0`-special by deleting `2` occurrences of `"a"` and `1` occurrence of `"c"`. Therefore, `word` becomes equal to `"baba"` where `freq('a') == freq('b') == 2`.

Solution: C++ 100% Faster | Easy Step By Step Explanation

  1. Character Frequency Count: create a hash table to store the frequency of each character in the string word.
  2. Frequency Array and Sorting: Sort the frequency.
  3. Iterative Comparison.

Now, let's discuss about how could we iterate the list.
word=dadbdcbdcdcd k=2, the sorted character frequency list is [5,3,2,1], respectively representing the count of d,c,b,a.

Let's construct the K-Special string:

  • (based on d) d is 5, diff = 0(5-5); c is 3, drop c; b is 2, beacuse b < d, and we can't add the number of b (question require delete char, so based on d, we can't construct a string dddddbbbbb) to the number of d, we need drop all b, so we need delete 2 chars; a is 1, the same sitution as b, so we need to delete 1 char. totally delete 3 + 2 + 1 = 6 chars when we construct the K-Special String based on d, the word is ddddd;
  • (based on c) d is 5, diff = 2 (<=k); c is 3, diff = 0(<=k); b is 2, beacuse b < c, we need drop all b; a is 1, we need drop all a; number = 2 + 1 = 3, the word is dddddccc;
  • (based on b) d is 5, diff = 3 (>k), we need to delete 3-k=1 char, c is 3, diff = 1 (<=k); b is 2, diff = 0; a is 1, so we need to drop all a. deleted char number = 1 + 1 = 2, the word is ddddcccbb;
  • (based on a) d is 5, diff = 4(>k), delete 4 - k = 2 chars, c is 3, b is 2, a is 2, all diff is less than k, so deleted char number = 2, the word is dddcccbba;
  • So the result is 2;
fun minimumDeletions(word: String, k: Int): Int {
    val chars = IntArray(26)
    word.forEach {
        chars[it - 'a']++
    }
    // ascend or descend are fine.
    chars.sortDescending()
    var result = Integer.MAX_VALUE
    for (target in chars) {
        var tempRes = 0
        for (cur in chars) {
            // There are no letters after here.
            if (cur == 0) {
                break
            }
            if (cur < target) { // drop all chars less than target(base).

                tempRes += cur
            } else if (cur > target + k) { // delete the extra chars.
                tempRes += cur - (target + k)
            }
        }
        result = min(tempRes, result)
    }
    return result
}