455. Better Compression of String

Given a compressed string compressed representing a shortened version of an original string. The format consists of a character followed by its frequency. For example, "d5e2d2a4" is a compressed form of "dddddeeddaaaa".

The task is to return a better compression of the given string with the following conditions:

  • Each character should appear only once in the final output.
  • Characters should be sorted alphabetically in the output string.

Return the optimized compressed version of the string.

Example 1:

Input: compressed = "d4a3c2a2c5"

Output: "a5c7d4"

Explanation:

The letter "a" appears twice (a3 and a2), so its total count is 3 + 2 = 5.

The letter "c" appears twice (c2 and c5), so its total count is 2 + 5 = 7.

The letter "d" appears once (d4).

Sorting in alphabetical order, the result is "a5c7d4".

Example 2:

Input: compressed = "b6c4a2"

Output: "a2b6c4"

Explanation:

As all the characters appears once, the final result after sorting will be a2b6c4

Now Your Turn!

Pick the correct output for the given input

Input: compressed = "e3d4c2b1e2"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= compressed.length <= 5 × 104
  • compressed consists only of lowercase English letters and digits.
  • compressed is valid, meaning each character is always followed by its frequency.
  • Frequencies are in the range [1, 104] and do not have leading zeroes.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
string betterCompression(string compressed) {
}
};
Test Case

Input:

Compressed