
If the given string is “wwwmpp”, then, Run-length encoded string will be “w3mp2”,
Here, we replace ‘www’ with ‘w3’, as the frequency of ‘w’ is 3,
And, we replace ‘pp’ with ‘p2’, as the frequency of ‘p’ is 2,
Thus, the given string is compressed to “w3mp2”,
Note, for ‘m’ we are not adding 1 because it is mentioned in the definition of Run-Length Encoding, only 2 or more repeated character count will be concatenated.
Consider the string 'Str' = “cccdeeef” and 'K' =2,
Current Run-length encoded string is "c3de3f" having length 6.
Here we can delete at most 2 characters, so If we delete any of the characters 'c' or 'e', it would at most decrease the length of the compressed string to 5,
For example, if we delete 2 'c' then we will have the string "cdeeef" which can be compressed to “cde3f”. Therefore, the optimal way is to delete 'd' and 'f', then the compressed string will be "c3e3" of length 4.
The first line of input contains a single integer 'T', representing the number of test cases or queries to be run.
Then the 'T' test cases follow.
The first line of each test case contains a string 'STR'.
The second line of each test case contains a single integer 'K', representing the maximum deletions allowed in the string.
For each test case, print the length of the minimum compressed string after deleting at-most 'K' characters in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= |STR| <= 100
0 <= K <= |STR|
Where |STR| denotes the length of string 'STR'.
All the characters of the string will be in lowercase
Time Limit: 1 sec
We find all possible strings that can be obtained by deleting at most ‘K’ characters using a backtracking algorithm. Then one by one we compress all these strings and find the minimum length after compression.
Let Len(curIdx, K, prevChar, cntPrevChar) denote the minimum run-length-encoding obtained starting from index curIdx where K denotes the number of deletions remaining, prevChar denotes the last character with frequency cntPrevChar so far.
Now two possibilities exist, either to delete the current character or to retain it.
If K > 0 and we delete the current character then -:
If we retain the current character then there are two possible cases -:
In the previous approach, we can observe that we have done a lot of repeated work. To avoid repeated work we will store the result of already computed subproblems in a ‘dp’ table.
The ‘dp’ table will have four dimension dp[curIdx][K][prevChar][cntPrevChar] where curIdx: current index in, K: Remaining number of deletion, prevChar: a previous character we represent a character with an integer between 1 to 26., cntPrevChar: Number of occurrences of the previous character.