fork(1) download
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4.  
  5. std::string compress_string(const std::string& s)
  6. {
  7. std::string res;
  8. for (auto it = s.begin(); it != s.end(); ) {
  9. const auto next = std::find_if(it + 1, s.end(), [&](char c) { return *it != c; });
  10. const auto count = next - it;
  11. res += *it;
  12. if (count != 1) {
  13. res += std::to_string(count);
  14. }
  15. it = next;
  16. }
  17. return res;
  18. }
  19.  
  20.  
  21. int main() {
  22. std::cout << compress_string("abcde") << std::endl;
  23. std::cout << compress_string("aaaaaaaaaaaabbbbbbbbbbcccc") << std::endl;
  24. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
abcde
a12b10c4