pranay_teja
3/20/2019 - 10:48 AM

DCP-29

#include<bits/stdc++.h>
using namespace std;

// DCG-29

// Run-length encoding is a fast and simple method of encoding strings. 
// The basic idea is to represent repeated successive characters as a single count and character. 
// For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".

// Implement run-length encoding and decoding. You can assume the string to be encoded have no digits 
// and consists solely of alphabetic characters. You can assume the string to be decoded is valid.

// input:
// DDDDDDDDDDDDDDFFFFFF

// output:
// 14D6F
// DDDDDDDDDDDDDDFFFFFF

int str2int(string s){
    int place = 1;
    int num = 0;
    for(int i=s.size()-1;i>=0;i--){
        num += (s[i]-'0')*place;
        place *= 10;
    }
    return num;
}
string int2str(int n){
    string s;
    while(n>0){
        s.insert(s.begin()+0, (n%10) +'0');
        n /= 10;
    }
    return s;
}
string encode(string s){
    string enc;
    stack<char> st;
    int counter = 0;
    for(int i=0;i<s.size();i++){
        if( st.empty() || st.top() == s[i]){
            st.push(s[i]);
            counter++;
        }else{
            enc += int2str(counter);
            counter = 0; // reset
            enc.push_back(st.top());
            st.push(s[i]);
            counter++;
            // st.clear();
        }
        // for last remaining group
        if(i == s.size()-1){
            enc += int2str(counter);
            enc.push_back(st.top());
        }
    }
    return enc;
}

string decode(string enc){
    string dec;
    string num;
    for(int i=0;i<enc.size();i++){
        if(enc[i]-'0' >=0 && enc[i]-'0' <= 9){
            num.push_back(enc[i]);
        }else{
            int n = str2int(num);
            while(n--){
                dec.push_back(enc[i]);
            }
            num=""; // reset the number
        }
    }
    return dec;
}
int main(){
    freopen("ip.txt","r",stdin);
    int t;
    cin>>t;
    while(t--){
        string s;
        cin>>s;
        string enc =  encode(s);
        cout<<enc<<endl;
        cout<<decode(enc)<<endl;
    }
    return 0;
}