Problem · String
Shortest Compressed Length After Removal
Learn this problemProblem statement
A compressed representation replaces each maximal run of equal consecutive characters as follows:
- A run of length
1is represented by the character alone. - A run longer than
1is represented by its decimal length followed by the character.
For example, ABBBCCCC compresses to A3B4C.
Given a string S of length N and an integer K, remove exactly K consecutive characters from S. Return the shortest possible length of the compressed representation of the remaining string.
The brackets in each HTML diagram mark the consecutive characters removed in that example.
┌───────────────┐ ┌───────┐
│ ABBBCC[DDC]CC │ ──▶ │ A3B4C │
└───────────────┘ └───────┘┌──────────────────────────┐ ┌─────┐
│ AAAAAAAAAAA[BXX]AAAAAAAAAA │ ──▶ │ 21A │
└──────────────────────────┘ └─────┘┌────────────┐ ┌───────┐
│ ABCDDD[EF]G │ ──▶ │ ABC3DG │
└────────────┘ └───────┘Function
solution(S: String, K: int) → intExamples
Example 1
S = "ABBBCCDDCCC"K = 3return = 5Remove DDC to obtain ABBBCCCC. It compresses to A3B4C, whose length is 5.
Example 2
S = "AAAAAAAAAAABXXAAAAAAAAAA"K = 3return = 3Remove BXX to leave twenty-one consecutive A characters. They compress to 21A, whose length is 3.
Example 3
S = "ABCDDDEFG"K = 2return = 6Remove EF to obtain ABCDDDG. It compresses to ABC3DG, whose length is 6.