Decode a string recursively encoded as count followed by substring | Set 2 (using Recursion)
Last Updated :
09 Jan, 2023
An encoded string str is given. The pattern in which the string is encoded is as follows.
<count>[sub_str] ==> The substring ‘sub_str’ appears count times.
The task is to decode this string str.
Examples:
Input: str = “1[b]”
Output: b
Explanation: The substring ‘b’ is repeated 1 time.
Input: str = “2[ab]”
Output: abab
Explanation: The substring “ab” is repeated two times.
Input: str = “2[a2[b]]”
Output: abbabb
Explanation: The substring ‘b’ is repeated 2 times and added to ‘a’ which forms a substring “abb”.
Now this substring is repeated two time. So the final string is “abbabb”.
Iterative Approach: The iterative approach is mentioned in the Set-1 of this problem.
Recursive Approach: In this article, the problem will be solved using Recursion and Stack. Follow the approach mentioned below to solve the problem
- Declare a stack
- Recursively traverse each character of the given string one by one. There can be 4 cases:
- Case 1: Current character is ‘[‘
- No need to do anything in this case. Just continue to next character
- Case 2: Current character is ‘]’
- Pop the top string temp and top integer x from the stack
- Repeat the string temp, x times
- If the next top element in the stack is a string, append this repeated string to the top string
- else push the repeated string into the stack
- Case 3: Current character is a digit
- If previous char of original string was also a digit, append this digit to the number on top of the stack
- If previous char was something else, push this digit into the stack
- Case 4: Current character is an alphabet
- If previous char of original string was also an alphabet, append this alphabet to the string on top of the stack
- If previous char was something else, push this alphabet into the stack
- At the end, return the string in the stack and print it
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
stack<string> ans;
string res = "" ;
void decode(string s, int i)
{
if (i == s.length()) {
res = ans.top();
return ;
}
if (s[i] == '[' );
else if (s[i] == ']' ) {
string temp = ans.top();
ans.pop();
int x = stoi(ans.top());
ans.pop();
for (string j = temp; x > 1; x--)
temp = temp + j;
string temp1
= ans.empty() == false ?
ans.top() : "" ;
if (!temp1.empty() &&
!(temp1[0] - '0' < 10)) {
ans.pop();
temp1 = temp1 + temp;
ans.push(temp1);
}
else {
ans.push(temp);
}
}
else if (s[i] - '0' < 10) {
string temp =
ans.empty() == false ?
ans.top() : "" ;
if (!temp.empty() &&
temp[0] - '0' < 10
&& s[i - 1] - '0' < 10) {
ans.pop();
temp = temp + s[i];
ans.push(temp);
}
else {
temp = s[i];
ans.push(temp);
}
}
else if (s[i] - 'a' < 26) {
string temp =
ans.empty() == false ?
ans.top() : "" ;
if (!temp.empty() &&
temp[0] - 'a' >= 0
&& temp[0] - 'a' < 26) {
ans.pop();
temp = temp + s[i];
ans.push(temp);
}
else {
temp = s[i];
ans.push(temp);
}
}
decode(s, i + 1);
}
string decodeString(string s)
{
decode(s, 0);
return res;
}
int main()
{
string str = "2[a2[b]]" ;
cout << decodeString(str) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static Stack<String> ans = new Stack<String>();
static String res = "" ;
static void decode( char [] s, int i)
{
if (i == s.length) {
res = ans.peek();
return ;
}
if (s[i] == '[' );
else if (s[i] == ']' ) {
String temp = ans.peek();
ans.pop();
int x = Integer.valueOf(ans.peek());
ans.pop();
for (String j = temp; x > 1 ; x--)
temp = temp + j;
String temp1
= ans.isEmpty() == false ?
ans.peek() : "" ;
if (!temp1.isEmpty() &&
!(temp1.charAt( 0 ) - '0' < 10 )) {
ans.pop();
temp1 = temp1 + temp;
ans.add(temp1);
}
else {
ans.add(temp);
}
}
else if (s[i] - '0' < 10 ) {
String temp =
ans.isEmpty() == false ?
ans.peek() : "" ;
if (!temp.isEmpty() &&
temp.charAt( 0 ) - '0' < 10
&& s[i - 1 ] - '0' < 10 ) {
ans.pop();
temp = temp + s[i];
ans.add(temp);
}
else {
temp = String.valueOf(s[i]);
ans.add(temp);
}
}
else if (s[i] - 'a' < 26 ) {
String temp =
ans.isEmpty() == false ?
ans.peek() : "" ;
if (!temp.isEmpty() &&
temp.charAt( 0 ) - 'a' >= 0
&& temp.charAt( 0 ) - 'a' < 26 ) {
ans.pop();
temp = temp + s[i];
ans.add(temp);
}
else {
temp = String.valueOf(s[i]);
ans.add(temp);
}
}
decode(s, i + 1 );
}
static String decodeString(String s)
{
decode(s.toCharArray(), 0 );
return res;
}
public static void main(String[] args)
{
String str = "2[a2[b]]" ;
System.out.print(decodeString(str) + "\n" );
}
}
|
Python3
ans = []
res = ""
def decode(s, i):
global res
global ans
if (i = = len (s)):
res = ans[ len (ans) - 1 ]
return
if (s[i] = = '[' ):
pass
elif (s[i] = = ']' ):
temp = ans[ len (ans) - 1 ]
ans.pop()
x = int (ans[ len (ans) - 1 ])
ans.pop()
j = temp
while (x> 1 ):
temp = temp + j
x - = 1
temp1 = ans[ len (ans) - 1 ] if len (ans) ! = 0 else ""
if len (temp1) ! = 0 and ~( ord (temp1[ 0 ]) - ord ( '0' ) < 10 ):
ans.pop()
temp1 = temp1 + temp
ans.append(temp1)
else :
ans.append(temp)
elif ( ord (s[i]) - ord ( '0' ) < 10 ):
temp = ans[ len (ans) - 1 ] if len (ans) ! = 0 else ""
if ( len (temp) ! = 0 and
ord (temp[ 0 ]) - ord ( '0' ) < 10 and
ord (s[i - 1 ]) - ord ( '0' ) < 10 ):
ans.pop()
temp = temp + s[i]
ans.append(temp)
else :
temp = s[i]
ans.append(temp)
elif ( ord (s[i]) - ord ( 'a' ) < 26 ):
temp = ans[ len (ans) - 1 ] if ( len (ans) ! = 0 ) else ""
if (temp ! = 0 and ord (temp[ 0 ]) - ord ( 'a' ) > = 0 and ord (temp[ 0 ]) - ord ( 'a' ) < 26 ):
ans.pop()
temp = temp + s[i]
ans.append(temp)
else :
temp = s[i]
ans.append(temp)
decode(s, i + 1 )
def decodeString(s):
decode(s, 0 )
return res
str = "2[a2[b]]"
print (decodeString( str ))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static Stack<String> ans = new Stack<String>();
static String res = "" ;
static void decode( char [] s, int i)
{
if (i == s.Length) {
res = ans.Peek();
return ;
}
if (s[i] == '[' );
else if (s[i] == ']' ) {
String temp = ans.Peek();
ans.Pop();
int x = int .Parse(ans.Peek());
ans.Pop();
for (String j = temp; x > 1; x--)
temp = temp + j;
String temp1
= ans.Count > 0 ? ans.Peek() : "" ;
if (temp1.Length > 0 &&
!(temp1[0] - '0' < 10)) {
ans.Pop();
temp1 = temp1 + temp;
ans.Push(temp1);
}
else {
ans.Push(temp);
}
}
else if (s[i] - '0' < 10) {
String temp =
ans.Count > 0 ?
ans.Peek() : "" ;
if (temp.Length > 0 &&
temp[0] - '0' < 10
&& s[i - 1] - '0' < 10) {
ans.Pop();
temp = temp + s[i];
ans.Push(temp);
}
else {
temp = char .ToString(s[i]);
ans.Push(temp);
}
}
else if (s[i] - 'a' < 26) {
String temp =
ans.Count > 0 ?
ans.Peek() : "" ;
if (temp.Length > 0 &&
temp[0] - 'a' >= 0
&& temp[0] - 'a' < 26) {
ans.Pop();
temp = temp + s[i];
ans.Push(temp);
}
else {
temp = char .ToString(s[i]);
ans.Push(temp);
}
}
decode(s, i + 1);
}
static String decodeString(String s)
{
decode(s.ToCharArray(), 0);
return res;
}
public static void Main()
{
String str = "2[a2[b]]" ;
Console.WriteLine(decodeString(str));
}
}
|
Javascript
<script>
let ans = [];
let res = "" ;
function decode(s, i)
{
if (i == s.length)
{
res = ans[ans.length - 1];
return ;
}
if (s[i] == '[' );
else if (s[i] == ']' )
{
let temp = ans[ans.length - 1];
ans.pop();
let x = (ans[ans.length - 1]);
ans.pop();
for (let j = temp; x > 1; x--)
temp = temp + j;
let temp1 = ans.length != 0 ?
ans[ans.length - 1] : "" ;
if (!temp1.length == 0 &&
!(temp1[0].charCodeAt(0) -
'0' .charCodeAt(0) < 10))
{
ans.pop();
temp1 = temp1 + temp;
ans.push(temp1);
}
else
{
ans.push(temp);
}
}
else if (s[i].charCodeAt(0) -
'0' .charCodeAt(0) < 10)
{
let temp = ans.length != 0 ?
ans[ans.length - 1] : "" ;
if (!temp.length == 0 &&
temp[0].charCodeAt(0) -
'0' .charCodeAt(0) < 10 &&
s[i - 1].charCodeAt(0) -
'0' .charCodeAt(0) < 10)
{
ans.pop();
temp = temp + s[i];
ans.push(temp);
}
else
{
temp = s[i];
ans.push(temp);
}
}
else if (s[i].charCodeAt(0) -
'a' .charCodeAt(0) < 26)
{
let temp = ans.length != 0 ?
ans[ans.length - 1] : "" ;
if (!temp.length == 0 &&
temp[0].charCodeAt(0) - 'a' .charCodeAt(0) >= 0 &&
temp[0].charCodeAt(0) - 'a' .charCodeAt(0) < 26)
{
ans.pop();
temp = temp + s[i];
ans.push(temp);
}
else
{
temp = s[i];
ans.push(temp);
}
}
decode(s, i + 1);
}
function decodeString(s)
{
decode(s, 0);
return res;
}
let str = "2[a2[b]]" ;
document.write(decodeString(str) + '<br>' );
</script>
|
Time Complexity: O(N) where N is the length of the decoded string
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...