An Odd Question about String Compression
I was scheduled to take a coding interview today and I bombed it so hard. The first question was regarding binary search (LC medium) and the twist was the search space was floating point numbers. I solved it but in 112 test cases, 2 were error . I am not sure if it was floating point issue or not. However, the second question caught me completely clueless. I am posting the question here. Apparently I also found this question in stack overflow but the solution did not seem optimal. Dear LeetCode community, can you please explain the solution of the following problem please? Thanks in advance.
Description:
Strings with long blocks of repeating characters take much less space if kept in a compressed representation. To obtain the compressed representation, we replace each segment of equal characters in the string with the number of characters in the segment followed by the character(e.x we replace segment "CCCC" with 4C). To avoid increasing the size, we leave the one-letter segments unchanged(the compressed representation of "BC" is the same string - "BC"). For example, the compressed representation of the string "ABBBCCDDCCC" is "A3B2C2D3C", and the compressed representation of the string "AAAAAAAAAAABXXAAAAAAAAAA" is "11AB2X10A". Observe that, in the second example, if we removed the "BXX" segment from the middle of the word, we would obtain a much shorter compressed representation - "21A". In order to take advantage of this observation, we decided to modify the compression algorithm. Now before compression, we remove exactly K consecutive letters from the input string. We would like to know the shortest compressed form that we can generate this way.
Write a function:
class Solution {
public int solution(String S, int K) {
}
} that given a string S of length N and an integer K, returns the shortest possible length of the compressed representation of S after removing exactly K consecutive characters from S.
Example:
Given S = "AAAAAAAAAAABXXAAAAAAAAAA" and K=3, the function should return 3, because after removing "BXX" from S, we are left with "AAAAAAAAAAAAAAAAAAAAA", which compresses to a representation of length 3 - "21A".
Requirement:
N is an integer within the range [1...100,000];
K is an integer within the range [0...100,000];
K <= N;
string S consists only of uppercase letters (A-Z)
