fork(2) download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <utility>
  5. #include <algorithm>
  6. #include <cassert>
  7. using namespace std;
  8.  
  9. typedef pair<char, uint8_t> RunLength;
  10.  
  11. vector<RunLength> runLengthEncode(const string& s) {
  12. if(s == "") return {};
  13. vector<RunLength> res;
  14.  
  15. size_t i = 0, nextPos;
  16. while(s.npos != (nextPos = s.find_first_not_of(s[i], i + 1)) ) {
  17. auto diff = nextPos - i;
  18. assert(diff <= 255);
  19. res.push_back( {s[i], diff} );
  20. i = nextPos;
  21. }
  22. res.push_back( {s[i], s.size() - i} );
  23. return res;
  24. }
  25.  
  26. string runLengthDecode(const vector<RunLength>& encoding) {
  27. string res;
  28. auto addFun = [&res](const RunLength& rl) {
  29. res += string(rl.second, rl.first);
  30. };
  31. for_each(encoding.begin(), encoding.end(), addFun);
  32. return res;
  33. }
  34.  
  35. int main() {
  36. cout << runLengthDecode(runLengthEncode("All your base are belong to us!")) << "\n";
  37. }
Success #stdin #stdout 0s 3064KB
stdin
Standard input is empty
stdout
All your base are belong to us!