String Compression 2 Problem
Problem
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc"
we replace "aa"
by "a2"
and replace "ccc"
by "c3"
. Thus the compressed string becomes "a2bc3"
.
Notice that in this problem, we are not adding '1'
after single characters.
Given a string s
and an integer k
. You need to delete at most k
characters from s
such that the run-length encoded version of s
has minimum length.
Find the minimum length of the run-length encoded version of s
after deleting at most k
characters.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - DP
We use dp[i][j]
to denote the states, which is the best solution up until s[i]
with at most j
characters removed.
For each character, we want to try all the solutions with removing at most j
in [0, k]
characters:
- Try to remove the current character if we can (
j > 0
): removing the current character is always easier. We can transfer from the state of:dp[i - 1][j - 1]
- Keep the current character in the final solution, and try to remove at most
j
different characters before the current character to form our chain. In the process of removal, we also count the number of characterscnt
in our chain. So in every positionp
, we may transfer from a better state ofdp[p - 1][j - removed] + calcLen(cnt)
, which means to append our chain of lengthcnt
, after the substring ofs.substring(0, p)
withj - removed
characters removed (since we have removedremoved
characters in order to form our chain, we leave onlyj - removed
for the previous substring).
Code
|
|
Complexity
- Time:
O(kn^2)
- Space:
O(kn)