For the given strings (not containing numbers), print their shortened versions, where each adjacent sequence of the same characters longer than 2, change to an expression consisting of a sign and a number of repetitions.
Sample input:
4
AAA
ABCDEF
CCCCCCDDDDDDD
ZZAACCCDDDDEEEEEE
Sample output:
A3
ABCDEF
C6D7
ZZAAC3D4E6
My code:
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>
std::string reduce(std::string const& word) {
std::string result;
for (auto it = word.cbegin(); true;) {
auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
auto dist = std::distance(it, curr) + (curr != word.cend());
if (dist < 3) {
result += std::string(dist, *it);
} else {
result += *it + std::to_string(dist);
}
if (curr == word.cend()) {
break;
}
it = 1 + curr;
}
return result;
}
int main() {
std::size_t tests;
std::cin >> tests;
while (tests--) {
std::string word;
std::cin >> word;
std::cout << reduce(word) << "\n";
}
}
How could I simplify or improve this code?