Decode

Given an encrypted message, Erwin encodes it the following way:

Removes the median letter of the word from the original word and appends it to the end of the encrypted word and repeats the process until there are no letters left.

A median letter in a word is the letter present in the middle of the word and if the word length is even, the median letter is the left one out of the two middle letters.

Given an encoded string, write a program to decode it.

Example:

Input:  s = "wrien"
Output: erwin

Approach

C++

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

string decode(string s)
{
    int i = 0;
    string res;
    res.resize(s.size());
    int nmxflag = 0;
    while (i < s.size())
    {
        x = s.size() - i;
        if (x & 1)
        {
            if (flag == 0)
            {
                res[res.size() / 2] = s[i];
                flag = 1;
                n = res.size() / 2 - 1;
                m = res.size() / 2 + 1;
            }
            else
            {
                res[m] = s[i];
                m++;
            }
        }
        else
        {
            if (flag == 0)
            {
                res[res.size() / 2 - 1] = s[i];
                flag = 1;
                n = res.size() / 2 - 2;
                m = res.size() / 2;
            }
            else
            {
                res[n] = s[i];
                n--;
            }
        }
        i++;
    }
    return res;
}
int main()
{

    string s = "wrien";

    cout << decode(s<< "\n";

    return 0;
}


No comments:

Post a Comment