fork download
  1. #include <iostream>
  2. #include <string> // It's good practice to include string and to_string
  3.  
  4. using namespace std;
  5.  
  6. int main() {
  7. string s;
  8. cin >> s;
  9.  
  10. // Handle empty string edge case
  11. if (s.empty()) {
  12. return 0;
  13. }
  14.  
  15. string ans = "";
  16. ans += s[0];
  17. int cnt = 1;
  18.  
  19. for (int i = 1; i < s.size(); i++) {
  20. if (s[i] == s[i - 1]) {
  21. // If current char is the same as the previous, just increase count
  22. cnt++;
  23. } else {
  24. // If it's different, append the previous count, then the new char
  25. ans += to_string(cnt);
  26. ans += s[i];
  27. cnt = 1; // Reset count for the new character
  28. }
  29. }
  30.  
  31. // Don't forget to append the count of the very last character sequence!
  32. ans += to_string(cnt);
  33.  
  34. cout << ans << endl;
  35. return 0;
  36. }
Success #stdin #stdout 0.01s 5324KB
stdin
wffrbtrjyuy
stdout
w1f2r1b1t1r1j1y1u1y1