fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. string collapseInput(string s) {
  5. // If string is empty
  6. if (s.empty()) {
  7. return "";
  8. }
  9.  
  10. string result = "";
  11. int count = 1;
  12.  
  13. for (int i = 1; i < s.length(); i++) {
  14. if (s[i] == s[i - 1]) {
  15. count++;
  16. } else {
  17. // Append count and character
  18. result += to_string(count);
  19. result += s[i - 1];
  20.  
  21. // Reset count
  22. count = 1;
  23. }
  24. }
  25.  
  26. // Add last group
  27. result += to_string(count);
  28. result += s[s.length() - 1];
  29.  
  30. return result;
  31. }
  32.  
  33. int main() {
  34. string s;
  35. cin >> s;
  36.  
  37. cout << collapseInput(s);
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0.01s 5296KB
stdin
GGGGGrrrrrrrrrrrrrrt
stdout
5G14r1t