📜  根据给定规则解密字符串

📅  最后修改于: 2021-06-26 17:38:39             🧑  作者: Mango

给定加密的字符串str ,任务是在加密规则如下时解密给定的字符串:

  1. 从原始字符串的第一个字符开始。
  2. 在每个奇怪的步骤中,在其后附加下一个字符。
  3. 到目前为止,在每个偶数步骤中,将下一个字符到加密的字符串。

例子:

方法:可以按照相反的顺序执行给出的加密字符串的步骤,以获得原始字符串。获取原始字符串将有两个条件:

  • 如果字符串的长度为奇数,请在奇数步中将字符从后面添加到结果字符串,否则从前面添加。
  • 如果字符串是偶数长度,在从偶数步骤背部的前部和附加字符奇数步骤的附加字符

如此获得的结果字符串的反向是原始字符串,该原始字符串已加密。
下面是上述方法的实现:

C++
// C++ program to decrypt the original string
#include 
using namespace std;
 
// Function to return the original string
// after decryption
string decrypt(string s, int l)
{
    // Stores the decrypted string
    string ans = "";
 
    // If length is odd
    if (l % 2) {
 
        // Step counter
        int cnt = 0;
 
        // Starting and ending index
        int indl = 0, indr = l - 1;
 
        // Iterate till all characters
        // are decrypted
        while (ans.size() != l) {
 
            // Even step
            if (cnt % 2 == 0)
                ans += s[indl++];
 
            // Odd step
            else
                ans += s[indr--];
 
            cnt++;
        }
    }
 
    // If length is even
    else {
 
        // Step counter
        int cnt = 0;
 
        // Starting and ending index
        int indl = 0, indr = l - 1;
        while (ans.size() != l) {
 
            // Even step
            if (cnt % 2 == 0)
                ans += s[indr--];
 
            // Odd step
            else
                ans += s[indl++];
 
            cnt++;
        }
    }
 
    // Reverse the decrypted string
    reverse(ans.begin(), ans.end());
 
    return ans;
}
 
// Driver Code
int main()
{
    string s = "segosegekfrek";
    int l = s.length();
    cout << decrypt(s, l);
 
    return 0;
}


Java
// Java program to decrypt the original string
import java.io.*;
import java.util.*;
 
class GFG
{
 
  // Function to return the original string
  // after decryption
  public static String decrypt(String s, int l)
  {
     
    // Stores the decrypted string
    String ans = "";
 
    // If length is odd
    if (l % 2 == 1)
    {
 
      // Step counter
      int cnt = 0;
 
      // Starting and ending index
      int indl = 0, indr = l - 1;
 
      // Iterate till all characters
      // are decrypted
      while (ans.length() != l)
      {
 
        // Even step
        if (cnt % 2 == 0)
          ans += s.charAt(indl++);
 
        // Odd step
        else
          ans += s.charAt(indr--);
        cnt++;
      }
    }
 
    // If length is even
    else
    {
 
      // Step counter
      int cnt = 0;
 
      // Starting and ending index
      int indl = 0, indr = l - 1;
      while (ans.length() != l)
      {
 
        // Even step
        if (cnt % 2 == 0)
          ans += s.charAt(indr--);
 
        // Odd step
        else
          ans += s.charAt(indl++);
 
        cnt++;
      }
    }
 
    // Reverse the decrypted string
    StringBuffer sbr = new StringBuffer(ans);
    sbr.reverse();
    return sbr.toString();
  }
 
  // Driver code
  public static void main (String[] args)
  {
    String s = "segosegekfrek";
    int l = s.length();
    System.out.println(decrypt(s, l));
  }
}
 
// This Code is contributed by Manu Pathria


Python3
# Python3 program to decrypt
# the original string
 
# Function to return the
# original string after
# decryption
def decrypt(s, l):
 
    # Stores the decrypted
    # string
    ans = ""
 
    # If length is odd
    if (l % 2):
 
        # Step counter
        cnt = 0
 
        # Starting and ending
        # index
        indl = 0
        indr = l - 1
 
        # Iterate till all
        # characters are decrypted
        while (len(ans) != l):
 
            # Even step
            if (cnt % 2 == 0):
                ans += s[indl]
                indl += 1
 
            # Odd step
            else:
                ans += s[indr]
                indr -= 1
 
            cnt += 1
 
    # If length is even
    else:
 
        # Step counter
        cnt = 0
 
        # Starting and ending
        # index
        indl = 0
        indr = l - 1
        while (len(ans) != l):
 
            # Even step
            if (cnt % 2 == 0):
                ans += s[indr]
                indr -= 1
 
            # Odd step
            else:
                ans += s[indl]
                indl += 1
 
            cnt += 1
 
    # Reverse the decrypted
    # string
    string = list(ans)
    string.reverse()
    ans = ''.join(string)
 
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    s = "segosegekfrek"
    l = len(s)
    print(decrypt(s, l))
 
# This code is contributed by Chitranayal


Python3
#Python 3 Code for encrypting a string according to given rules
#Function for encryption
def encrypted_string(strg):
    EncryptedString = [strg[0]]
    for t in range(1,len(strg)):
        if (t%2 == 1):
            EncryptedString.append(strg[t]) #At odd position, append the next character
        else:
            EncryptedString.insert(0,strg[t]) #At Even position, prepend the next character
    #print the resultant string
    return (''.join(EncryptedString))
 
 
#Python 3 Code for decrypting a string (Answer to the actual question)
def decrypted_string(strg):
    #CHeck the divisibility of length of string by 2
    if (len(strg)%2!=0):
        DecryptedString = [strg[0]]
        for t in range(1,len(strg)):
            DecryptedString.append(strg[-1*t]) #First add the characters from the back
            DecryptedString.append(strg[t]) #from the front
        DecryptedString = DecryptedString[:len(strg)][::-1] #Reverse the final string to get output
        return (''.join(DecryptedString))
    else:
        reverse_strg = strg[::-1] #In case of even length, reverse the given string first
        DecryptedString=[reverse_strg[0]]
 
        #Looping over the reversed string
        for t in range(1,len(reverse_strg)):
            DecryptedString.append(reverse_strg[-1*t]) #First add the characters from the back
            DecryptedString.append(reverse_strg[t]) #and then from the front
        DecryptedString = DecryptedString[:len(reverse_strg)][::-1]
        return (''.join(DecryptedString))
     
     
#Testing the algorithm with Driver Code
if __name__== '__main__':
     
    print (encrypted_string('geeks'))
    print (encrypted_string('geeksforgeeks'))
    print (encrypted_string('strive'))
    print (encrypted_string('vikaschitturi'))
    print (encrypted_string('padmachitturi'))
    print (encrypted_string('hackerrank'))
    print (encrypted_string('hackerearth'))
    print (encrypted_string('codechef'))
    print (encrypted_string('IamVikas'))
    print (encrypted_string('HelloHowareyou'))
    print (encrypted_string('whatareyoudoing'))
 
    print(decrypted_string('segek'))
    print(decrypted_string('segosegekfrek'))
    print(decrypted_string('vrstie'))
    print(decrypted_string('iuthskviacitr'))
    print(decrypted_string('iuthadpamcitr'))
    print(decrypted_string('nrechakrak'))
    print(decrypted_string('hreechakrat'))
    print(decrypted_string(encrypted_string('IamVikas')))
    print(decrypted_string(encrypted_string('HelloHowareyou')))
    print(decrypted_string(encrypted_string('whatareyoudoing')))


输出:
geeksforgeeks

以下是Python的实现。

Python3

#Python 3 Code for encrypting a string according to given rules
#Function for encryption
def encrypted_string(strg):
    EncryptedString = [strg[0]]
    for t in range(1,len(strg)):
        if (t%2 == 1):
            EncryptedString.append(strg[t]) #At odd position, append the next character
        else:
            EncryptedString.insert(0,strg[t]) #At Even position, prepend the next character
    #print the resultant string
    return (''.join(EncryptedString))
 
 
#Python 3 Code for decrypting a string (Answer to the actual question)
def decrypted_string(strg):
    #CHeck the divisibility of length of string by 2
    if (len(strg)%2!=0):
        DecryptedString = [strg[0]]
        for t in range(1,len(strg)):
            DecryptedString.append(strg[-1*t]) #First add the characters from the back
            DecryptedString.append(strg[t]) #from the front
        DecryptedString = DecryptedString[:len(strg)][::-1] #Reverse the final string to get output
        return (''.join(DecryptedString))
    else:
        reverse_strg = strg[::-1] #In case of even length, reverse the given string first
        DecryptedString=[reverse_strg[0]]
 
        #Looping over the reversed string
        for t in range(1,len(reverse_strg)):
            DecryptedString.append(reverse_strg[-1*t]) #First add the characters from the back
            DecryptedString.append(reverse_strg[t]) #and then from the front
        DecryptedString = DecryptedString[:len(reverse_strg)][::-1]
        return (''.join(DecryptedString))
     
     
#Testing the algorithm with Driver Code
if __name__== '__main__':
     
    print (encrypted_string('geeks'))
    print (encrypted_string('geeksforgeeks'))
    print (encrypted_string('strive'))
    print (encrypted_string('vikaschitturi'))
    print (encrypted_string('padmachitturi'))
    print (encrypted_string('hackerrank'))
    print (encrypted_string('hackerearth'))
    print (encrypted_string('codechef'))
    print (encrypted_string('IamVikas'))
    print (encrypted_string('HelloHowareyou'))
    print (encrypted_string('whatareyoudoing'))
 
    print(decrypted_string('segek'))
    print(decrypted_string('segosegekfrek'))
    print(decrypted_string('vrstie'))
    print(decrypted_string('iuthskviacitr'))
    print(decrypted_string('iuthadpamcitr'))
    print(decrypted_string('nrechakrak'))
    print(decrypted_string('hreechakrat'))
    print(decrypted_string(encrypted_string('IamVikas')))
    print(decrypted_string(encrypted_string('HelloHowareyou')))
    print(decrypted_string(encrypted_string('whatareyoudoing')))

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。