Program to find the Encrypted word
Last Updated :
02 Feb, 2023
Given a string, the given string is an encrypted word, the task is to decrypt the given string to get the original word. Examples:
Input: str = “abcd”
Output: bdee
Explanation:
a -> a + 1 -> b
b -> b + 2 -> d
c -> c + 2 -> e
d -> d + 1 -> e
Input: str = “xyz”
Output: yaa
Explanation:
x -> x + 1 -> y
y -> y + 2 -> a
z -> z + 1 -> a
Approach:
- Let the length of the string be n.
- then the encrypted string will be:
- Print the string after finding the scrypted word.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findWord(string c, int n)
{
int co = 0, i;
string s(n, ' ' );
for (i = 0; i < n; i++) {
if (i < n / 2)
co++;
else
co = n - i;
if (c[i] + co <= 122)
s[i] = ( char )(( int )c[i] + co);
else
s[i] = ( char )(( int )c[i] + co - 26);
}
cout << s;
}
int main()
{
string s = "abcd" ;
findWord(s, s.length());
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG
{
public static void findWord(String c, int n)
{
int co = 0 , i;
char s[] = new char [n];
for (i = 0 ; i < n ; i++)
{
if (i < n / 2 )
co++;
else
co = n - i;
if ((c.charAt(i) + co) <= 122 )
s[i] = ( char )(( int )c.charAt(i) + co);
else
s[i] = ( char )(( int )c.charAt(i) + co - 26 );
}
String str = Arrays.toString(s);
System.out.println(str);
}
public static void main(String args[])
{
String s = "abcd" ;
findWord(s, s.length());
}
}
|
Python3
def findWord(c, n):
co = 0
s = [ 0 ] * n
for i in range (n):
if (i < n / 2 ):
co + = 1
else :
co = n - i
if ( ord (c[i]) + co < = 122 ):
s[i] = chr ( ord (c[i]) + co)
else :
s[i] = chr ( ord (c[i]) + co - 26 )
print ( * s, sep = "")
s = "abcd"
findWord(s, len (s))
|
C#
using System;
class GFG
{
public static void findWord(String c, int n)
{
int co = 0, i;
char []s = new char [n];
for (i = 0; i < n ; i++)
{
if (i < n / 2)
co++;
else
co = n - i;
if ((c[i] + co) <= 122)
s[i] = ( char )(( int )c[i] + co);
else
s[i] = ( char )(( int )c[i] + co - 26);
}
String str = String.Join( "" ,s);
Console.WriteLine(str);
}
public static void Main(String []args)
{
String s = "abcd" ;
findWord(s, s.Length);
}
}
|
Javascript
function findWord(c, n) {
let co = 0, i;
let s = new Array(n).fill( ' ' );
for (i = 0; i < n; i++) {
if (i < n / 2)
co++;
else
co = n - i;
if (c.charCodeAt(i) + co <= 122)
s[i] = String.fromCharCode(c.charCodeAt(i) + co);
else
s[i] = String.fromCharCode(c.charCodeAt(i) + co - 26);
}
console.log(s.join( '' ));
}
let s = "abcd" ;
findWord(s, s.length);
|
Time Complexity: O(N)
Auxiliary Space: O(N), The extra space is used to store the result.
Share your thoughts in the comments
Please Login to comment...