[LeetCode] Better Compression of String

3167. Better Compression of String

You are given a string compressed representing a compressed version of a string. The format is a character followed by its frequency. For example, "a3b1a1c2" is a compressed version of the string "aaabacc".

We seek a better compression with the following conditions:

  1. Each character should appear only once in the compressed version.
  2. The characters should be in alphabetical order.

Return the better compression of compressed.

Note: In the better version of compression, the order of letters may change, which is acceptable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
string betterCompression(string s) {
map<char,long long> ord;
for(int i = 0; i < s.length();) {
char ch = s[i];
i++;
long long now = 0;
while(i < s.length() and isdigit(s[i])) {
now = now * 10 + s[i] - '0';
i++;
}
if(now == 0) now = 1;
ord[ch] += now;
}
string res = "";
for(auto& [k,v] : ord) {
res.push_back(k);
res += to_string(v);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/06/26/PS/LeetCode/better-compression-of-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.