fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5.  
  6. vector<string> compress(vector<char>& chars) {
  7. int n = chars.size();
  8. vector<string> result;
  9.  
  10. for (int i = 0; i < n; ) {
  11. char currentChar = chars[i];
  12. int count = 0;
  13.  
  14. // Count repetitions
  15. int j = i;
  16. while (j < n && chars[j] == currentChar) {
  17. count++;
  18. j++;
  19. }
  20.  
  21. // Build entry
  22. if (count == 1) {
  23. result.push_back(string(1, currentChar));
  24. } else {
  25. result.push_back(currentChar + to_string(count));
  26. }
  27.  
  28. i = j;
  29. }
  30.  
  31. return result;
  32. }
  33. int main() {
  34. vector<char> input = {'a', 'a', 'b', 'c', 'c', 'c'};
  35.  
  36. vector<string> compressed = compress(input);
  37. cout << "Compressed vector of strings: ";
  38. for (const string& s : compressed) {
  39. cout << s << " ";
  40. }
  41. cout << endl;
  42.  
  43. return 0;
  44. }
  45.  
Success #stdin #stdout 0s 5288KB
stdin
10
aba
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
stdout
Compressed vector of strings: a2 b c3