Run-length encoding compresses a string by replacing each group of consecutive identical characters (repeated 2 or more times) with the character followed by the number of times it repeats (the length of the run). For example, to compress "aabccc", replace "aa" with "a2" and "ccc" with "c3". The compressed string is "a2bc3". A single character is written alone, with no '1' after it.
Given a string s and an integer k, delete at most k characters from s so that the run-length encoded version of what remains is as short as possible. Return the minimum length of that encoded string.
Function Signature
def min_compressed_length(s: str, k: int) -> int:
Rules
-
You may delete any characters at any positions, up to
k
of them in total (zero deletions is allowed). The remaining characters keep their original order.
-
A run of one character encodes as that character alone, with length 1. A run of
c >= 2
characters encodes as the character followed by the decimal digits of
c
, so
"a12"
has length 3.
-
Return only the length as an integer. If every character is deleted, the encoded string is empty and the answer is 0.
Constraints
-
1 <= len(s) <= 100
-
0 <= k <= len(s)
-
s
contains only lowercase English letters.
Examples
Input: s = "aaabcccd", k = 2
Output: 4
Deleting 'b' and 'd' leaves "aaaccc", which encodes to "a3c3" (length 4). At least six characters remain after two deletions and no letter appears more than three times, so two runs of three is the best possible.
Input: s = "aabbaa", k = 2
Output: 2
Deleting both 'b' characters joins the two runs of 'a' into "aaaa", which encodes to "a4". At least four characters remain, so the encoding cannot be a single character.
Input: s = "aaaaaaaaaa", k = 1
Output: 2
Keeping all ten characters gives "a10" (length 3). Deleting one leaves nine, which encodes to "a9" (length 2), and a length of 1 would require deleting all but one character.