Decodificar una string mediana a la string original

Dada una string s escrita en forma de mediana, cámbiela de nuevo a la string original. La letra mediana en una string es la letra que está en el medio de la string. Si la longitud de la string es par, la letra mediana está a la izquierda de las dos letras del medio. La string dada se forma escribiendo la letra mediana de la palabra, luego borrándola y repitiendo el proceso hasta que no queden letras. 

Ejemplos:  

Input: eekgs
Output: geeks 
Explanation: in the original string “geeks” 
can be written in median form by picking up 
e first then, again e, then k then g and at
the end s. As these are the median when the
median letter is picked and deleted. 

Input: abc 
Output: bac 
Explanation: median of bac is a, then median
of bc is b, then median of c is c.  

Para encontrar la respuesta, podemos iterar a través de la string codificada dada de izquierda a derecha y agregar cada letra en la string de respuesta, una letra al principio, la siguiente letra al final, la siguiente letra al comienzo, y así sucesivamente. Si n es par entonces se debe agregar la primera letra al principio y la segunda letra al final. En el otro caso, la primera letra al final, la segunda al principio. Necesitamos hacerlo hasta que no agreguemos todas las letras de la string dada. 

Nota : para strings con longitud uniforme, cuando agregamos el primer carácter al principio y el segundo carácter al final, la string restante siempre tendrá la misma longitud. Lo mismo es cierto para strings con longitudes impares.

A continuación se muestra la implementación del enfoque anterior. 

C++

// C++ program to decode a median string
// to the original string
 
#include <bits/stdc++.h>
using namespace std;
 
// function to calculate the median back string
string decodeMedianString(string s)
{
    // length of string
    int l = s.length();
 
    // initialize a blank string
    string s1 = "";
 
    // Flag to check if length is even or odd
    bool isEven = (l % 2 == 0)? true : false;
 
    // traverse from first to last
    for (int i = 0; i < l; i += 2) {
 
        // if len is even then add first character
        // to beginning of new string and second
        // character to end
        if (isEven) {  
            s1 = s[i] + s1;
            s1 += s[i + 1];
        } else {
 
            // if current length is odd and is
            // greater than 1
            if (l - i > 1) {
 
                // add first character to end and
                // second character to beginning
                s1 += s[i];
                s1 = s[i + 1] + s1;
            } else {
 
                // if length is 1, add character 
                // to end
                s1 += s[i];
            }
        }
    }
 
    return s1;
}
 
// driver program
int main()
{
    string s = "eekgs";
    cout << decodeMedianString(s);
    return 0;
}

Java

// java program to decode a median
// string to the original string
 
public class GFG {
     
    // function to calculate the
    // median back string
    static String decodeMedianString(String s)
    {
         
        // length of string
        int l = s.length();
     
        // initialize a blank string
        String s1 = "";
     
        // Flag to check if length is
        // even or odd
        boolean isEven = (l % 2 == 0) ?
                          true : false;
     
        // traverse from first to last
        for (int i = 0; i < l; i += 2)
        {
     
            // if len is even then add
            // first character to
            // beginning of new string
            // and second character to
            // end
            if (isEven) {
                s1 = s.charAt(i) + s1;
                s1 += s.charAt(i+1);
            }
            else {
     
                // if current length is
                // odd and is greater
                // than 1
                if (l - i > 1) {
     
                    // add first character
                    // to end and second
                    // character to
                    // beginning
                    s1 += s.charAt(i);
                    s1 = s.charAt(i+1) + s1;
                }
                else {
     
                    // if length is 1,
                    // add character
                    // to end
                    s1 += s.charAt(i);
                }
            }
        }
     
        return s1;
    }
     
    // Driver code
    public static void main(String args[])
    {
        String s = "eekgs";
         
        System.out.println(
                    decodeMedianString(s));
    }
}
 
// This code is contributed by Sam007.

Python3

# Python3 program to decode a median
# string to the original string
 
# function to calculate the median
# back string
def decodeMedianString(s):
     
    # length of string
    l = len(s)
 
    # initialize a blank string
    s1 = ""
 
    # Flag to check if length is
    # even or odd
    if(l % 2 == 0):
        isEven = True
    else:
        isEven = False
 
    # traverse from first to last
    for i in range(0, l, 2):
         
        # if len is even then add first
        # character to beginning of new
        # string and second character to end
        if (isEven):
            s1 = s[i] + s1
            s1 += s[i + 1]
        else :
             
            # if current length is odd and
            # is greater than 1
            if (l - i > 1):
                 
                # add first character to end and
                # second character to beginning
                s1 += s[i]
                s1 = s[i + 1] + s1
            else:
                 
                # if length is 1, add character
                # to end
                s1 += s[i]
 
    return s1
 
# Driver Code
if __name__ == '__main__':
    s = "eekgs"
    print(decodeMedianString(s))
 
# This code is contributed by
# Sanjit_Prasad

C#

// C# program to decode a median
// string to the original string
using System;
 
class GFG {
     
    // function to calculate the
    // median back string
    static string decodeMedianString(string s)
    {
         
        // length of string
        int l = s.Length;
     
        // initialize a blank string
        string s1 = "";
     
        // Flag to check if length is
        // even or odd
        bool isEven = (l % 2 == 0) ?
                         true : false;
     
        // traverse from first to last
        for (int i = 0; i < l; i += 2)
        {
     
            // if len is even then add
            // first character to
            // beginning of new string
            // and second character to
            // end
            if (isEven) {
                s1 = s[i] + s1;
                s1 += s[i + 1];
            }
            else {
     
                // if current length is
                // odd and is greater
                // than 1
                if (l - i > 1) {
     
                    // add first character
                    // to end and second
                    // character to
                    // beginning
                    s1 += s[i];
                    s1 = s[i + 1] + s1;
                }
                else {
     
                    // if length is 1,
                    // add character
                    // to end
                    s1 += s[i];
                }
            }
        }
     
        return s1;
    }
 
    // Driver code
    public static void Main ()
    {
        string s = "eekgs";
        Console.WriteLine(
               decodeMedianString(s));
    }
}
 
// This code is contributed by Sam007.

Javascript

<script>
// javascript program to decode a median
// string to the original string
 
 
 
    // function to calculate the
    // median back string
    function decodeMedianString( s) {
 
        // length of string
        var l = s.length;
 
        // initialize a blank string
        var s1 = "";
 
        // Flag to check if length is
        // even or odd
        var isEven = (l % 2 == 0) ? true : false;
 
        // traverse from first to last
        for (i = 0; i < l; i += 2) {
 
            // if len is even then add
            // first character to
            // beginning of new string
            // and second character to
            // end
            if (isEven) {
                s1 = s.charAt(i) + s1;
                s1 += s.charAt(i + 1);
            } else {
 
                // if current length is
                // odd and is greater
                // than 1
                if (l - i > 1) {
 
                    // add first character
                    // to end and second
                    // character to
                    // beginning
                    s1 += s.charAt(i);
                    s1 = s.charAt(i + 1) + s1;
                } else {
 
                    // if length is 1,
                    // add character
                    // to end
                    s1 += s.charAt(i);
                }
            }
        }
 
        return s1;
    }
 
    // Driver code
     
        var s = "eekgs";
 
        document.write(decodeMedianString(s));
 
// This code contributed by Rajput-Ji
</script>
Producción

geeks

Complejidad de tiempo: O (N), ya que estamos usando un bucle para atravesar N veces.
Espacio auxiliar: O(1) , ya que no estamos utilizando ningún espacio adicional.

Este artículo es una contribución de Striver . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *