Skip to content

Add Run Length Encoding and Decoding [#2719] #2968

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions strings/run_length_encoding.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <iostream>
#include <string>
using namespace std;

// Run Length Encoding
string encode(const string& input) {
string encoded = "";
int n = input.length();
for (int i = 0; i < n; i++) {
int count = 1;
while (i < n - 1 && input[i] == input[i + 1]) {
count++;
i++;
}
encoded += input[i] + to_string(count);
}
return encoded;
}

// Run Length Decoding
string decode(const string& input) {
string decoded = "";
int n = input.length();
for (int i = 0; i < n; i += 2) {
char ch = input[i];
int count = input[i + 1] - '0';
decoded += string(count, ch);
}
return decoded;
}

// Driver code
int main() {
string original = "aaabbcdddd";
string encoded = encode(original);
string decoded = decode(encoded);

cout << "Original: " << original << endl;
cout << "Encoded: " << encoded << endl;
cout << "Decoded: " << decoded << endl;

return 0;
}