string compression: aaabbbbcc ->a3b4c2
string string_compression(const string& s) {
if(s.empty()) return "";
unordered_map<char, int> hash;
for(char c : s) hash[c]++;
string res;
for(auto p : hash) {
if(p.second == 1)
res += p.first;
else
res += p.first + to_string(p.second);
}
return res;
}
string string_compression2(const string& s) {
char last_char = s[0];
string res;
int i = 1; // start from second
int count = 1;
while(i < s.size()) {
if(s[i] == last_char)
count++;
else {
res += last_char + to_string(count);
last_char = s[i];
count = 1;
}
i++;
}
res += last_char + to_string(count); // cannot forget
return res;
}