Decrypt message from given code by replacing all * with prefix values of encoded string
Last Updated :
29 Dec, 2021
Given a string str of length of N that is in the encoded form with alphabets and * . The task is to find the string from which it was generated. The required string can be generated from the encoded string by replacing all the * with the prefix values of the encoded string.
Examples:
Input: str = ab*c*d
Output: “ababcababcd”
Explanation: For the first occurrence of “*”, “ab” is the prefix. So ‘*’ is replaced by “ab” resulting the string to be “ababc*d” and for the next ‘*‘ the prefix is “ababc”. So the string will now change from “ababc*d” to “ababcababcd”.
Input : str = “z*z*z”
Output: zzzzzzz
Approach: The solution is based on greedy approach. Follow the steps mentioned below to solve the problem:
- Consider an empty string result.
- Iterate over the given coded string.
- if the current character in the string is not “*” then add the current character to the result.
- Otherwise, if the current character is “*”, add the result string formed till now with itself.
- Return the result.
Below is the implementation of the given approach.
C++
#include <bits/stdc++.h>
using namespace std;
string findstring(string str)
{
string result = "" ;
for ( int i = 0; str[i] != '\0' ; i++) {
if (str[i] == '*' )
result += result;
else
result += str[i];
}
return result;
}
int main()
{
string str = "ab*c*d" ;
cout << findstring(str);
return 0;
}
|
Java
class GFG {
static String findstring(String str)
{
String result = "" ;
for ( int i = 0 ; i < str.length(); i++) {
if (str.charAt(i) == '*' )
result += result;
else
result += str.charAt(i);
}
return result;
}
public static void main(String[] args)
{
String str = "ab*c*d" ;
System.out.println(findstring(str));
}
}
|
Python3
def findstring( str ):
result = ""
for i in range ( len ( str )):
if ( str [i] = = '*' ):
result + = result
else :
result + = str [i]
return result
str = "ab*c*d"
print (findstring( str ))
|
C#
using System;
class GFG
{
static string findstring( string str)
{
string result = "" ;
for ( int i = 0; i < str.Length; i++)
{
if (str[i] == '*' )
result += result;
else
result += str[i];
}
return result;
}
public static void Main()
{
string str = "ab*c*d" ;
Console.Write(findstring(str));
}
}
|
Javascript
<script>
function findstring(str) {
let result = "" ;
for (let i = 0; i < str.length; i++) {
if (str[i] == '*' )
result += result;
else
result += str[i];
}
return result;
}
let str = "ab*c*d" ;
document.write(findstring(str));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...