Encrypt a string by repeating i-th character i times
Last Updated :
08 Aug, 2022
Given string str, the task is to encrypt the string with the given encryption algorithm. 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.
Examples:
Input: str = "geeks"
Output: geeeeekkkksssss
Input: str = "abcd"
Output: abbcccdddd
Approach: Initialize cnt = 1 and start traversing the string character by character. Repeat the current character cnt number of times then update cnt = cnt + 1 and get to the next character. Repeat these steps for every character of the string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string encryptString(string str, int n)
{
int i = 0, cnt = 0;
string encryptedStr = "" ;
while (i < n) {
cnt = i + 1;
while (cnt--)
encryptedStr += str[i];
i++;
}
return encryptedStr;
}
int main()
{
string str = "geeks" ;
int n = str.length();
cout << encryptString(str, n);
return 0;
}
|
Java
class GFG
{
static String encryptString(String str, int n)
{
int i = 0 , cnt = 0 ;
String encryptedStr = "" ;
while (i < n)
{
cnt = i + 1 ;
while (cnt-- > 0 )
encryptedStr += str.charAt(i);
i++;
}
return encryptedStr;
}
public static void main(String[] args)
{
String str = "geeks" ;
int n = str.length();
System.out.println(encryptString(str, n));
}
}
|
Python3
def encryptString(string, n):
i, cnt = 0 , 0
encryptedStr = ""
while i < n:
cnt = i + 1
while cnt > 0 :
encryptedStr + = string[i]
cnt - = 1
i + = 1
return encryptedStr
if __name__ = = "__main__" :
string = "geeks"
n = len (string)
print (encryptString(string, n))
|
C#
using System;
class GFG
{
static String encryptString(String str, int n)
{
int i = 0, cnt = 0;
String encryptedStr = "" ;
while (i < n)
{
cnt = i + 1;
while (cnt-- >0)
encryptedStr += str[i];
i++;
}
return encryptedStr;
}
static public void Main ()
{
String str = "geeks" ;
int n = str.Length;
Console.WriteLine(encryptString(str, n));
}
}
|
PHP
<?php
function encryptString( $str , $n )
{
$i = 0 ;
$cnt = 0;
$encryptedStr = "" ;
while ( $i < $n )
{
$cnt = $i + 1;
while ( $cnt --)
$encryptedStr .= $str [ $i ];
$i ++;
}
return $encryptedStr ;
}
$str = "geeks" ;
$n = strlen ( $str );
echo encryptString( $str , $n );
?>
|
Javascript
<script>
function encryptString(str, n)
{
let i = 0, cnt = 0;
let encryptedStr = "" ;
while (i < n)
{
cnt = i + 1;
while (cnt-- >0)
encryptedStr += str[i];
i++;
}
return encryptedStr;
}
let str = "geeks" ;
let n = str.length;
document.write(encryptString(str, n));
</script>
|
Time Complexity: O(n) // n is the length of the string
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...