Decrypt message from given code by replacing all * with prefix values of encoded string
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.
Input: str = ab*c*d
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”
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.
Time Complexity: O(N)
Auxiliary Space: O(N)