Decrypt a string encrypted by repeating i-th character i times
Given an encrypted string str and the encryption algorithm, the task is to decrypt the string. The encryption algorithm is as follows:
The 1st character of the string will be repeated once in the encrypted string, the 2nd character will be repeated twice, …, nth character will be repeated n times. For example, the string “abcd” will be encrypted as “abbcccdddd”.
Examples:
Input: str = “geeeeekkkksssss”
Output: geeks
Input: str = “abbcccdddd”
Output: abcd
Approach: Initialize i = 0 and print str[i].
Update i = i + 1 and print str[i], then update i = i + 2 and print str[i] and so on while i < length(str).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string decryptString(string str, int n)
{
int i = 0, jump = 1;
string decryptedStr = "" ;
while (i < n) {
decryptedStr += str[i];
i += jump;
jump++;
}
return decryptedStr;
}
int main()
{
string str = "geeeeekkkksssss" ;
int n = str.length();
cout << decryptString(str, n);
return 0;
}
|
Java
class GFG
{
static String decryptString(String str, int n)
{
int i = 0 , jump = 1 ;
String decryptedStr = "" ;
while (i < n)
{
decryptedStr += str.charAt(i);
i += jump;
jump++;
}
return decryptedStr;
}
public static void main(String[] args)
{
String str = "geeeeekkkksssss" ;
int n = str.length();
System.out.println(decryptString(str, n));
}
}
|
Python3
def decryptString( str , n):
i = 0
jump = 1
decryptedStr = ""
while (i < n):
decryptedStr + = str [i];
i + = jump
jump + = 1
return decryptedStr
if __name__ = = '__main__' :
str = "geeeeekkkksssss"
n = len ( str )
print (decryptString( str , n))
|
C#
using System;
class GFG
{
static string decryptString( string str, int n)
{
int i = 0, jump = 1;
string decryptedStr = "" ;
while (i < n)
{
decryptedStr += str[i];
i += jump;
jump++;
}
return decryptedStr;
}
public static void Main()
{
string str = "geeeeekkkksssss" ;
int n = str.Length;
Console.Write(decryptString(str, n));
}
}
|
PHP
<?php
function decryptString( $str , $n )
{
$i = 0 ;
$jump = 1 ;
$decryptedStr = "" ;
while ( $i < $n )
{
$decryptedStr .= $str [ $i ];
$i += $jump ;
$jump ++;
}
return $decryptedStr ;
}
$str = "geeeeekkkksssss" ;
$n = strlen ( $str );
echo decryptString( $str , $n );
?>
|
Javascript
<script>
function decryptString(str,n)
{
let i = 0, jump = 1;
let decryptedStr = "" ;
while (i < n)
{
decryptedStr += str[i];
i += jump;
jump++;
}
return decryptedStr;
}
let str = "geeeeekkkksssss" ;
let n = str.length;
document.write(decryptString(str, n));
</script>
|
Time Complexity: O(?n), where n is the length of the given string.
Auxiliary Space: O(?n), where n is the length of the given string.
Last Updated :
13 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...