You are given a compressed string s in which each lowercase letter is followed by its positive integer frequency count. Return a better compressed string in which the characters appear in alphabetical order with their total combined frequencies.
If the same character appears more than once in the input, its counts are summed in the output.
The output uses the same format: each character followed by its total count, sorted alphabetically by character.
Function Signature
def better_compression(s: str) -> str:
Rules
-
A count is the whole run of digits after a letter, so
c10
means letter
c
with count 10.
-
Each distinct letter appears exactly once in the output, followed by its total written in decimal with no leading zeros.
Constraints
-
1 <= len(s) <= 1000
-
s
consists of lowercase English letters and digits.
-
Each letter is followed by a positive integer count.
-
The format is always valid: a letter followed by one or more digits, repeating.
Examples
Input: s = "a3c9b2c1"
Output: "a3b2c10"
Letter a has count 3, b has count 2, and c has counts 9 and 1 for a total of 10. Sorted alphabetically, that gives "a3b2c10".
Input: s = "z1a1b1a2"
Output: "a3b1z1"
Letter a has counts 1 and 2 (total 3), b has count 1 and z has count 1. Sorting puts z last even though it came first in the input.
Input: s = "b12a3b8"
Output: "a3b20"
The counts for b are 12 and 8, both read as whole numbers, so its total is 20. Letter a has count 3 and sorts first.