String Compression II

Hard Topics Company Tags

Delete at most k characters from the lowercase string s, keeping the order of all remaining characters. Then encode each consecutive run as its character followed by the run length, omitting the length when it is 1. For example, bbbaa becomes b3a2, while abc stays abc. Return the shortest possible encoded length after the deletions. Deleting every character produces an empty encoding of length 0.

Example 1:

Input: s = "bbbaac"
k = 1

Output: 4

Explanation: Delete the final c, leaving bbbaa. Its encoding is b3a2, which has length 4. A single deletion cannot reduce this example below length 4.

Example 2:

Input: s = "aaaa"
k = 4

Output: 0

Explanation: Delete all four characters. The remaining string and its encoding are empty, so the length is 0.

Example 3:

Input: s = "aabbaa"
k = 2

Output: 2

Explanation: Delete both b characters to join the two a runs. The remaining aaaa encodes as a4, with length 2.

Constraints:

  • 1 <= s.length <= 100
  • 0 <= k <= s.length
  • s contains only lowercase English letters.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.