Given a string str of lowercase alphabets only. The task is to replace every character by some new character. The new character belongs to
(small case only) Replacement of str[i] is determined by:
str[i] = Character obtained after traversing ascii(str[i]) no. of characters in ‘a-z’ repeatedly after str[i].
Examples:
Input: str = “geeksforgeeks”
Output: fbbnddvbfbbnd
In the above case str = “geeksforgeeks”,
the ASCII value of ‘g’ is 103 therefore ‘g’ has been replaced by moving 103 times from ‘g’ in the desired range i.e., a-z.
Hence, character ‘g’ is replaced by ‘f’.
Similarly, the complete string “geeksforgeeks” becomes “fbbnddvbfbbnd”.
Input: str = “science”
Output: dxjbtxb
Approach:
- Traverse the string.
- For every i, find the character that needs to be replaced with str[i].
- Replace str[i] with that character.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void manipulateString(string &str)
{
for ( int i = 0; i < str.length(); i++) {
int asc = str[i];
int rem = asc - (26 - (str[i] - 'a' ));
int m = rem % 26;
str[i] = ( char )(m + 'a' );
}
}
int main()
{
string str = "geeksforgeeks" ;
manipulateString(str);
cout << str;
return 0;
}
|
Java
public class GFG {
static void manipulateString(String str)
{
char [] str1 = str.toCharArray();
for ( int i = 0 ; i < str.length(); i++) {
int asc = str1[i];
int rem = asc - ( 26 - (str1[i] - 97 ));
int m = rem % 26 ;
str1[i] = ( char )(m + 'a' );
}
String str2 = String.valueOf(str1);
System.out.println(str2);
}
public static void main(String[] args) {
String str = "geeksforgeeks" ;
manipulateString(str);
}
}
|
Python 3
def manipulateString( str ) :
for i in range ( len ( str )) :
asc = ord ( str [i])
rem = asc - ( 26 - ( ord ( str [i]) - ord ( 'a' )))
m = rem % 26
str [i] = chr (m + ord ( 'a' ))
print (''.join( str ))
if __name__ = = "__main__" :
str = "geeksforgeeks"
str = list ( str )
manipulateString( str )
|
C#
using System;
public class GFG {
static void manipulateString(String str)
{
char [] str1 = str.ToCharArray();
for ( int i = 0; i < str.Length; i++) {
int asc = str1[i];
int rem = asc - (26 - (str1[i] - 97));
int m = rem % 26;
str1[i] = ( char )(m + 'a' );
}
String str2 = String.Join( "" ,str1);
Console.WriteLine(str2);
}
public static void Main() {
String str = "geeksforgeeks" ;
manipulateString(str);
}
}
|
Javascript
<script>
function manipulateString(str)
{
for ( var i = 0; i < str.length; i++) {
var asc = str[i];
var rem = asc.charCodeAt(0) - (26 - (str[i].charCodeAt(0) - 'a' .charCodeAt(0)));
var m = (rem % 26);
str[i] = String.fromCharCode(m + 'a' .charCodeAt(0));
}
return str;
}
var str = "geeksforgeeks" ;
document.write(manipulateString(str.split( '' )).join( '' ));
</script>
|
Complexity Analysis:
- Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.
- Auxiliary Space: O(1), as we are not using any extra space.