fork download
  1. #include <iostream>
  2. #include <stack>
  3. #include <unordered_map>
  4. #include <cstdlib>
  5. std::string encode(const std::string inputstr) {
  6. std::string encoded_str;
  7. std::unordered_map<char, int> str_umap;
  8.  
  9. for (int i = 0; i < inputstr.size() ; i++) {
  10. char key = inputstr.at(i);
  11. auto it = str_umap.find(key);
  12. if(it == str_umap.end()) { // key not in msp
  13. str_umap[key] = 1;
  14. } else {
  15. str_umap[key] += 1;
  16. }
  17. //Not at end of string
  18. if (i != inputstr.size() - 1) {
  19. //Detect if run is over
  20. if(inputstr.at(i) != inputstr.at(i + 1)) {
  21. if(str_umap[key] == 1) {
  22. encoded_str += key;
  23. } else {
  24. encoded_str += key + std::to_string(str_umap[key]);
  25. }
  26. str_umap.clear();
  27. }
  28. } else {
  29. if(str_umap[key] == 1) {
  30. encoded_str += key;
  31. } else {
  32. encoded_str += key + std::to_string(str_umap[key]);
  33. }
  34. str_umap.clear();
  35. }
  36. }
  37.  
  38. return encoded_str;
  39.  
  40. }
  41.  
  42. std::string decode(const std::string encodedstr) {
  43. std::string decoded_str;
  44. char alpha = encodedstr.at(0);
  45. decoded_str += alpha;
  46. int num_of_times = 0;
  47. for (int i = 1; i < encodedstr.size() ; i++) {
  48. if(std::isdigit(encodedstr.at(i))) {
  49. num_of_times = static_cast<char>(encodedstr.at(i)) - '0';
  50. std::cout << num_of_times << "\n";
  51. } else {
  52. for (int j = 0; j < num_of_times ; j++) {
  53. decoded_str += alpha;
  54. }
  55. num_of_times = 0;
  56. alpha = encodedstr.at(i);
  57. }
  58. }
  59. return decoded_str;
  60. }
  61.  
  62. int main() {
  63. std::string mystring = "AAAABBBAC111c";
  64. std::cout << "Input string : " << mystring << "\n";
  65. std::string encoded = encode(mystring);
  66. std::cout << "Encoded string : " << encoded << "\n";
  67. std::string decoded = decode(encoded);
  68. std::cout << "Decoded string : " << decoded << "\n";
  69. return 0;
  70. }
Success #stdin #stdout 0s 4396KB
stdin
Standard input is empty
stdout
Input string : AAAABBBAC111c
Encoded string : A4B3AC13c
4
3
1
3
Decoded string : AAAAABBBCCC