The Wayback Machine - https://web.archive.org/web/20240530013253/https://www.geeksforgeeks.org/decode-string-recursively-encoded-count-followed-substring/
Open In App

Decode a string recursively encoded as count followed by substring

Last Updated : 23 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

An encoded string (s) is given, the task is to decode it. The pattern in which the strings are encoded is as follows. 

<count>[sub_str] ==> The substring 'sub_str' 
appears count times.

Examples:  

Input : str[] = "1[b]"
Output : b
Input : str[] = "2[ab]"
Output : abab
Input : str[] = "2[a2[b]]"
Output : abbabb
Input : str[] = "3[b2[ca]]"
Output : bcacabcacabcaca
Recommended Practice

The idea is to use two stacks, one for integers and another for characters. 
Now, traverse the string, 

  1. Whenever we encounter any number, push it into the integer stack and in case of any alphabet (a to z) or open bracket (‘[‘), push it onto the character stack.
  2. Whenever any close bracket (‘]’) is encounter pop the character from the character stack until open bracket (‘[‘) is not found in the character stack. Also, pop the top element from the integer stack, say n. Now make a string repeating the popped character n number of time. Now, push all character of the string in the stack.

Below is the implementation of this approach:  

C++
// C++ program to decode a string recursively
// encoded as count followed substring
#include<bits/stdc++.h>
using namespace std;

// Returns decoded string for 'str'
string decode(string str)
{
    stack<int> integerstack;
    stack<char> stringstack;
    string temp = "", result = "";

    // Traversing the string
    for (int i = 0; i < str.length(); i++)
    {
        int count = 0;

        // If number, convert it into number
        // and push it into integerstack.
        if (str[i] >= '0' && str[i] <='9')
        {
            while (str[i] >= '0' && str[i] <= '9')
            {
                count = count * 10 + str[i] - '0';
                i++;
            }

            i--;
            integerstack.push(count);
        }

        // If closing bracket ']', pop element until
        // '[' opening bracket is not found in the
        // character stack.
        else if (str[i] == ']')
        {
            temp = "";
            count = 0;

            if (! integerstack.empty())
            {
                count = integerstack.top();
                integerstack.pop();
            }

            while (! stringstack.empty() && stringstack.top()!='[' )
            {
                temp = stringstack.top() + temp;
                stringstack.pop();
            }

            if (! stringstack.empty() && stringstack.top() == '[')
                stringstack.pop();

            // Repeating the popped string 'temo' count
            // number of times.
            for (int j = 0; j < count; j++)
                result = result + temp;

            // Push it in the character stack.
            for (int j = 0; j < result.length(); j++)
                stringstack.push(result[j]);

            result = "";
        }

        // If '[' opening bracket, push it into character stack.
        else if (str[i] == '[')
        {
            if (str[i-1] >= '0' && str[i-1] <= '9')
                stringstack.push(str[i]);

            else
            {
                stringstack.push(str[i]);
                integerstack.push(1);
            }
        }

        else
            stringstack.push(str[i]);
    }

    // Pop all the element, make a string and return.
    while (! stringstack.empty())
    {
        result = stringstack.top() + result;
        stringstack.pop();
    }

    return result;
}

// Driven Program
int main()
{
    string str = "3[b2[ca]]";
    cout << decode(str) << endl;
    return 0;
}
Java
// Java program to decode a string recursively
// encoded as count followed substring

import java.util.Stack;

class Test
{
    // Returns decoded string for 'str'
    static String decode(String str)
    {
        Stack<Integer> integerstack = new Stack<>();
        Stack<Character> stringstack = new Stack<>();
        String temp = "", result = "";
     
        // Traversing the string
        for (int i = 0; i < str.length(); i++)
        {
            int count = 0;
     
            // If number, convert it into number
            // and push it into integerstack.
            if (Character.isDigit(str.charAt(i)))
            {
                while (Character.isDigit(str.charAt(i)))
                {
                    count = count * 10 + str.charAt(i) - '0';
                    i++;
                }
     
                i--;
                integerstack.push(count);
            }
     
            // If closing bracket ']', pop element until
            // '[' opening bracket is not found in the
            // character stack.
            else if (str.charAt(i) == ']')
            {
                temp = "";
                count = 0;
     
                if (!integerstack.isEmpty())
                {
                    count = integerstack.peek();
                    integerstack.pop();
                }
     
                while (!stringstack.isEmpty() && stringstack.peek()!='[' )
                {
                    temp = stringstack.peek() + temp;
                    stringstack.pop();
                }
     
                if (!stringstack.empty() && stringstack.peek() == '[')
                    stringstack.pop();
     
                // Repeating the popped string 'temo' count
                // number of times.
                for (int j = 0; j < count; j++)
                    result = result + temp;
     
                // Push it in the character stack.
                for (int j = 0; j < result.length(); j++)
                    stringstack.push(result.charAt(j));
     
                result = "";
            }
     
            // If '[' opening bracket, push it into character stack.
            else if (str.charAt(i) == '[')
            {
                if (Character.isDigit(str.charAt(i-1)))
                    stringstack.push(str.charAt(i));
     
                else
                {
                    stringstack.push(str.charAt(i));
                    integerstack.push(1);
                }
            }
     
            else
                stringstack.push(str.charAt(i));
        }
     
        // Pop all the element, make a string and return.
        while (!stringstack.isEmpty())
        {
            result = stringstack.peek() + result;
            stringstack.pop();
        }
     
        return result;
    }

    // Driver method
    public static void main(String args[])
    {
        String str = "3[b2[ca]]";
        System.out.println(decode(str));
    }
}
Python
# Python program to decode a string recursively 
# encoded as count followed substring 

# Returns decoded string for 'str' 
def decode(Str):
    integerstack = []
    stringstack = []
    temp = ""
    result = "" 
    i = 0
    # Traversing the string 
    while i < len(Str):
        count = 0

        # If number, convert it into number 
        # and push it into integerstack. 
        if (Str[i] >= '0' and Str[i] <='9'):
            while (Str[i] >= '0' and Str[i] <= '9'):
                count = count * 10 + ord(Str[i]) - ord('0') 
                i += 1
            i -= 1
            integerstack.append(count)

        # If closing bracket ']', pop element until 
        # '[' opening bracket is not found in the 
        # character stack. 
        elif (Str[i] == ']'):
            temp = "" 
            count = 0

            if (len(integerstack) != 0):
                count = integerstack[-1] 
                integerstack.pop()

            while (len(stringstack) != 0 and stringstack[-1] !='[' ):
                temp = stringstack[-1] + temp 
                stringstack.pop()

            if (len(stringstack) != 0 and stringstack[-1] == '['): 
                stringstack.pop() 

            # Repeating the popped string 'temo' count 
            # number of times.
            for j in range(count):
                result = result + temp 

            # Push it in the character stack.
            for j in range(len(result)):
                stringstack.append(result[j]) 

            result = ""

        # If '[' opening bracket, push it into character stack. 
        elif (Str[i] == '['):
            if (Str[i-1] >= '0' and Str[i-1] <= '9'): 
                stringstack.append(Str[i]) 

            else:
                stringstack.append(Str[i]) 
                integerstack.append(1)

        else:
            stringstack.append(Str[i])
        
        i += 1

    # Pop all the element, make a string and return.
    while len(stringstack) != 0:
        result = stringstack[-1] + result 
        stringstack.pop()

    return result

# Driven code 
if __name__ == '__main__':
    Str = "3[b2[ca]]"
    print(decode(Str))
    
# This code is contributed by PranchalK.
C#
// C# program to decode a string recursively 
// encoded as count followed substring 
using System;
using System.Collections.Generic;

class GFG
{
// Returns decoded string for 'str' 
public static string decode(string str)
{
    Stack<int> integerstack = new Stack<int>();
    Stack<char> stringstack = new Stack<char>();
    string temp = "", result = "";

    // Traversing the string 
    for (int i = 0; i < str.Length; i++)
    {
        int count = 0;

        // If number, convert it into number 
        // and push it into integerstack. 
        if (char.IsDigit(str[i]))
        {
            while (char.IsDigit(str[i]))
            {
                count = count * 10 + str[i] - '0';
                i++;
            }

            i--;
            integerstack.Push(count);
        }

        // If closing bracket ']', pop element 
        // until '[' opening bracket is not found 
        // in the character stack. 
        else if (str[i] == ']')
        {
            temp = "";
            count = 0;

            if (integerstack.Count > 0)
            {
                count = integerstack.Peek();
                integerstack.Pop();
            }

            while (stringstack.Count > 0 && 
                   stringstack.Peek() != '[')
            {
                temp = stringstack.Peek() + temp;
                stringstack.Pop();
            }

            if (stringstack.Count > 0 && 
                stringstack.Peek() == '[')
            {
                stringstack.Pop();
            }

            // Repeating the popped string 'temo' 
            // count number of times. 
            for (int j = 0; j < count; j++)
            {
                result = result + temp;
            }

            // Push it in the character stack. 
            for (int j = 0; j < result.Length; j++)
            {
                stringstack.Push(result[j]);
            }

            result = "";
        }

        // If '[' opening bracket, push it 
        // into character stack. 
        else if (str[i] == '[')
        {
            if (char.IsDigit(str[i - 1]))
            {
                stringstack.Push(str[i]);
            }

            else
            {
                stringstack.Push(str[i]);
                integerstack.Push(1);
            }
        }

        else
        {
            stringstack.Push(str[i]);
        }
    }

    // Pop all the element, make a 
    // string and return. 
    while (stringstack.Count > 0)
    {
        result = stringstack.Peek() + result;
        stringstack.Pop();
    }

    return result;
}

// Driver Code 
public static void Main(string[] args)
{
    string str = "3[b2[ca]]";
    Console.WriteLine(decode(str));
}
}

// This code is contributed by Shrikant13
Javascript
    // Javascript program to decode a string recursively 
    // encoded as count followed substring
    
    // Returns decoded string for 'str' 
    function decode(str)
    {
        let integerstack = [];
        let stringstack = [];
        let temp = "", result = "";

        // Traversing the string 
        for (let i = 0; i < str.length; i++)
        {
            let count = 0;

            // If number, convert it into number 
            // and push it into integerstack. 
            if (str[i] >= '0' && str[i] <='9')
            {
                while (str[i] >= '0' && str[i] <='9')
                {
                    count = count * 10 + str[i] - '0';
                    i++;
                }

                i--;
                integerstack.push(count);
            }

            // If closing bracket ']', pop element 
            // until '[' opening bracket is not found 
            // in the character stack. 
            else if (str[i] == ']')
            {
                temp = "";
                count = 0;

                if (integerstack.length > 0)
                {
                    count = integerstack[integerstack.length - 1];
                    integerstack.pop();
                }

                while (stringstack.length > 0 && 
                       stringstack[stringstack.length - 1] != '[')
                {
                    temp = stringstack[stringstack.length - 1] + temp;
                    stringstack.pop();
                }

                if (stringstack.length > 0 && 
                    stringstack[stringstack.length - 1] == '[')
                {
                    stringstack.pop();
                }

                // Repeating the popped string 'temo' 
                // count number of times. 
                for (let j = 0; j < count; j++)
                {
                    result = result + temp;
                }

                // Push it in the character stack. 
                for (let j = 0; j < result.length; j++)
                {
                    stringstack.push(result[j]);
                }

                result = "";
            }

            // If '[' opening bracket, push it 
            // into character stack. 
            else if (str[i] == '[')
            {
                if (str[i - 1] >= '0' && str[i - 1] <='9')
                {
                    stringstack.push(str[i]);
                }

                else
                {
                    stringstack.push(str[i]);
                    integerstack.push(1);
                }
            }

            else
            {
                stringstack.push(str[i]);
            }
        }

        // Pop all the element, make a 
        // string and return. 
        while (stringstack.length > 0)
        {
            result = stringstack[stringstack.length - 1] + result;
            stringstack.pop();
        }

        return result;
    }
    
    let str = "3[b2[ca]]";
    console.log((decode(str)));

// This code is contributed by divyeshrabadiy07.

Output
bcacabcacabcaca

Time Complexity: O(n)
Auxiliary Space: O(n)

<!—-Illustration of above code for “3[b2[ca]]”> 

Method 2(Using 1 stack)

Algorithm:
Loop through the characters of the string
If the character is not ']', add it to the stack
If the character is ']':
While top of the stack doesn't contain '[', pop the characters from the stack and store it in a string temp
(Make sure the string isn't in reverse order)
Pop '[' from the stack
While the top of the stack contains a digit, pop it and store it in dig
Concatenate the string temp for dig number of times and store it in a string repeat
Add the string repeat to the stack
Pop all the characters from the stack(also make the string isn't in reverse order)

Below is the implementation of this approach: 

C++
#include <iostream>
#include <stack>
using namespace std;

string decodeString(string s)
{
    stack<char> st;
    for (int i = 0; i < s.length(); i++) {
        // When ']' is encountered, we need to start
        // decoding
        if (s[i] == ']') {
            string temp;
            while (!st.empty() && st.top() != '[') {
                // st.top() + temp makes sure that the
                // string won't be in reverse order eg, if
                // the stack contains 12[abc temp = c + "" =>
                // temp = b + "c" => temp = a + "bc"
                temp = st.top() + temp;
                st.pop();
            }
            // remove the '[' from the stack
            st.pop();
            string num;
            // remove the digits from the stack
            while (!st.empty() && isdigit(st.top())) {
                num = st.top() + num;
                st.pop();
            }
            int number = stoi(num);
            string repeat;
            for (int j = 0; j < number; j++)
                repeat += temp;
            for (char c : repeat)
                st.push(c);
        }
        // if s[i] is not ']', simply push s[i] to the stack
        else
            st.push(s[i]);
    }
    string res;
    while (!st.empty()) {
        res = st.top() + res;
        st.pop();
    }
    return res;
}
// driver code
int main()
{
    string str = "3[b2[ca]]";
    cout << decodeString(str);
    return 0;
}
Java
import java.util.*;
public class Main
{
    static String decodeString(String s)
    {
        Vector<Character> st = new Vector<Character>();
        
        for(int i = 0; i < s.length(); i++)
        {
            
            // When ']' is encountered, we need to
            // start decoding
            if (s.charAt(i) == ']') 
            {
                String temp = "";
                while (st.size() > 0 && st.get(st.size() - 1) != '[')
                {
                    
                    // st.top() + temp makes sure that the
                    // string won't be in reverse order eg, if
                    // the stack contains 12[abc temp = c + "" =>
                    // temp = b + "c" => temp = a + "bc"
                    temp = st.get(st.size() - 1) + temp;
                    st.remove(st.size() - 1);
                }
                
                // Remove the '[' from the stack
                st.remove(st.size() - 1);
                String num = "";
                
                // Remove the digits from the stack
                while (st.size() > 0 && 
                       st.get(st.size() - 1) >= 48 && 
                       st.get(st.size() - 1) <= 57) 
                {
                    num = st.get(st.size() - 1) + num;
                    st.remove(st.size() - 1);
                }
                
                int number = Integer.parseInt(num);
                String repeat = "";
                for(int j = 0; j < number; j++)
                    repeat += temp;
                    
                for(int c = 0; c < repeat.length(); c++)
                    st.add(repeat.charAt(c));
            }
            
            // If s[i] is not ']', simply push
            // s[i] to the stack
            else
                st.add(s.charAt(i));
        }
        String res = "";
        while (st.size() > 0) 
        {
            res = st.get(st.size() - 1) + res;
            st.remove(st.size() - 1);
        }
        return res;
    }

    public static void main(String[] args) {
        String str = "3[b2[ca]]";
        System.out.print(decodeString(str));
    }
}

// This code is contributed by suresh07.
Python
def decodeString(s):
    st = []
    for i in range(len(s)):
      
        # When ']' is encountered, we need to start decoding
        if s[i] == ']':
            temp = ""
            while len(st) > 0 and st[-1] != '[':
              
                # st.top() + temp makes sure that the
                # string won't be in reverse order eg, if
                # the stack contains 12[abc temp = c + "" =>
                # temp = b + "c" => temp = a + "bc"
                temp = st[-1] + temp
                st.pop()
             
            # remove the '[' from the stack
            st.pop()
            num = ""
             
            # remove the digits from the stack
            while len(st) > 0 and ord(st[-1]) >= 48 and ord(st[-1]) <= 57:
                num = st[-1] + num
                st.pop()
            number = int(num)
            repeat = ""
            for j in range(number):
                repeat += temp
            for c in range(len(repeat)):
                if len(st) > 0:
                    if repeat == st[-1]:
                        break #otherwise this thingy starts appending the same decoded words 
                st.append(repeat)
          
        else:
            st.append(s[i])         
        
    return st[0]
 

Str = "3[b2[ca]]"
print(decodeString(Str))

# This code is contributed by mukesh07.
# And debugged by ivannakreshchenetska
C#
using System;
using System.Collections.Generic;

class GFG{

static string decodeString(string s)
{
    List<char> st = new List<char>();
    
    for(int i = 0; i < s.Length; i++)
    {
        
        // When ']' is encountered, we need to
        // start decoding
        if (s[i] == ']') 
        {
            string temp = "";
            while (st.Count > 0 && st[st.Count - 1] != '[')
            {
                
                // st.top() + temp makes sure that the
                // string won't be in reverse order eg, if
                // the stack contains 12[abc temp = c + "" =>
                // temp = b + "c" => temp = a + "bc"
                temp = st[st.Count - 1] + temp;
                st.RemoveAt(st.Count - 1);
            }
            
            // Remove the '[' from the stack
            st.RemoveAt(st.Count - 1);
            string num = "";
            
            // Remove the digits from the stack
            while (st.Count > 0 && 
                   st[st.Count - 1] >= 48 && 
                   st[st.Count - 1] <= 57) 
            {
                num = st[st.Count - 1] + num;
                st.RemoveAt(st.Count - 1);
            }
            
            int number = int.Parse(num);
            string repeat = "";
            for(int j = 0; j < number; j++)
                repeat += temp;
                
            foreach(char c in repeat)
                st.Add(c);
        }
        
        // If s[i] is not ']', simply push
        // s[i] to the stack
        else
            st.Add(s[i]);
    }
    string res = "";
    while (st.Count > 0) 
    {
        res = st[st.Count - 1] + res;
        st.RemoveAt(st.Count - 1);
    }
    return res;
}

// Driver code
static void Main() 
{
    string str = "3[b2[ca]]";
    Console.Write(decodeString(str));
}
}

// This code is contributed by decode2207
Javascript
    function decodeString(s)
    {
        let st = [];
        for (let i = 0; i < s.length; i++)
        {
        
            // When ']' is encountered, we need to start
            // decoding
            if (s[i] == ']') {
                let temp = "";
                while (st.length > 0 && st[st.length - 1] != '[')
                {
                
                    // st.top() + temp makes sure that the
                    // string won't be in reverse order eg, if
                    // the stack contains 12[abc temp = c + "" =>
                    // temp = b + "c" => temp = a + "bc"
                    temp = st[st.length - 1] + temp;
                    st.pop();
                }
                
                // remove the '[' from the stack
                st.pop();
                let num = "";
                
                // remove the digits from the stack
                while (st.length > 0 && st[st.length - 1].charCodeAt() >= 48 && st[st.length - 1].charCodeAt() <= 57) {
                    num = st[st.length - 1] + num;
                    st.pop();
                }
                let number = parseInt(num);
                let repeat = "";
                for (let j = 0; j < number; j++)
                    repeat += temp;
                for (let c = 0; c < repeat.length; c++)
                    st.push(repeat[c]);
            }
            
            // if s[i] is not ']', simply push s[i] to the stack
            else
                st.push(s[i]);
        }
        let res = "";
        while (st.length > 0) {
            res =  st[st.length - 1] + res;
            st.pop();
        }
        return res;
    }
    
    let str = "3[b2[ca]]";
    console.log(decodeString(str));

// This code is contributed by divyesh072019.

Output
bcacabcacabcaca

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 3: Without Stack

The given problem can be solved by traversing the encoded string character by character and maintaining a result string. Whenever a closing bracket is encountered, we can extract the substring enclosed within the corresponding opening bracket, and the number of times it needs to be repeated, and append the resulting string to the current result. We can continue this process until we reach the end of the input string.

Algorithm for better understanding.

  1. Initialize an empty string to store the decoded output.
  2. Traverse the input string character by character.
  3. If the current character is not a closing bracket ‘]’, add it to the output string.
  4. If the current character is a closing bracket, extract the substring enclosed within the corresponding opening bracket ‘[…]’, and the number of times it needs to be repeated say ‘num’.
  5. Append the resulting string to the output string num times.
  6. Repeat steps 3-5 until we reach the end of the input string.
  7. Return the decoded string.

Below is the implementation of the above idea.

C++
// C++ implementation to decode string without stack
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

// Function to decode given encoded string
string decodeString(string s)
{

    // Declare a string variable to store the decoded
    // string.
    string result = "";

    // Traverse the encoded string character by character.
    for (int i = 0; i < s.length(); i++) {

        // If the current character is not a closing
        // bracket, append it to the result string.
        if (s[i] != ']') {
            result.push_back(s[i]);
        }

        // If the current character is a closing bracket
        else {

            // Create a temporary string to store the
            // substring within the corresponding opening
            // bracket.
            string temp = "";
            while (!result.empty()
                   && result.back() != '[') {
                temp.push_back(result.back());
                result.pop_back();
            }

            // Reverse the temporary string to obtain the
            // correct substring.
            reverse(temp.begin(), temp.end());

            // Remove the opening bracket from the result
            // string.
            result.pop_back();

            // Extract the preceding number and convert it
            // to an integer.
            string num = "";
            while (!result.empty() && result.back() >= '0'
                   && result.back() <= '9') {
                num.push_back(result.back());
                result.pop_back();
            }
            reverse(num.begin(), num.end());
            int int_num = stoi(num);

            // Append the substring to the result string,
            // repeat it to the required number of times.
            while (int_num--) {
                result += temp;
            }
        }
    }

    // Return the decoded string.
    return result;
}

// driver code
int main()
{
    string str = "3[b2[ca]]";
    cout << decodeString(str);
    return 0;
}
Java
import java.util.Stack;

public class Main {

    // Function to decode given encoded string
    static String decodeString(String s) {
        // Declare a StringBuilder to store the decoded string
        StringBuilder result = new StringBuilder();

        // Traverse the encoded string character by character
        for (int i = 0; i < s.length(); i++) {
            // If the current character is not a closing bracket, append it to the result string
            if (s.charAt(i) != ']') {
                result.append(s.charAt(i));
            } else {
                // Create a temporary StringBuilder to store the substring within the corresponding opening bracket
                StringBuilder temp = new StringBuilder();
                while (result.length() > 0 && result.charAt(result.length() - 1) != '[') {
                    temp.insert(0, result.charAt(result.length() - 1));
                    result.deleteCharAt(result.length() - 1);
                }

                // Remove the opening bracket from the result string
                result.deleteCharAt(result.length() - 1);

                // Extract the preceding number and convert it to an integer
                StringBuilder num = new StringBuilder();
                while (result.length() > 0 && Character.isDigit(result.charAt(result.length() - 1))) {
                    num.insert(0, result.charAt(result.length() - 1));
                    result.deleteCharAt(result.length() - 1);
                }
                int int_num = Integer.parseInt(num.toString());

                // Append the substring to the result string, repeat it to the required number of times
                while (int_num-- > 0) {
                    result.append(temp);
                }
            }
        }

        // Return the decoded string
        return result.toString();
    }

    // Driver code
    public static void main(String[] args) {
        String str = "3[b2[ca]]";
        System.out.println(decodeString(str));
    }
}
Python
def decodeString(s):
    result = ""

    i = 0
    while i < len(s):
        if s[i] != ']':
            # If the current character is not a closing bracket, 
            # append it to the result string.
            result += s[i]
        else:
            # If the current character is a closing bracket:
            
            # Create a temporary string to store the substring within 
            # the corresponding opening bracket.
            temp = ""
            while len(result) > 0 and result[-1] != '[':
                # Keep popping characters from the result string and add them to the 
                # temp string until we reach the opening bracket.
                temp = result[-1] + temp
                result = result[:-1]

            result = result[:-1]  # Remove the opening bracket

            # Extract the preceding number and convert it to an integer.
            num = ""
            while len(result) > 0 and result[-1].isdigit():
                # Keep popping characters from the result string and add them to 
                # num string 
                # until we encounter a non-digit character.
                num = result[-1] + num
                result = result[:-1]
            int_num = int(num)

            # Append the substring to the result string, 
            # repeat it to the required number of times.
            while int_num > 0:
                result += temp
                int_num -= 1

        i += 1

    # Return the decoded string.
    return result

# Driver code to test the above function
str = "3[b2[ca]]"
print(decodeString(str))  # Output: "bcacabcacabca"
C#
// C# implementation to decode string without stack
using System;

public class GFG {
    // Function to decode given encoded string
    static string DecodeString(string s)
    {
        // Declare a string variable to store the decoded
        // string.
        string result = "";

        // Traverse the encoded string character by
        // character.
        for (int i = 0; i < s.Length; i++) {
            // If the current character is not a closing
            // bracket, append it to the result string.
            if (s[i] != ']') {
                result += s[i];
            }
            // If the current character is a closing bracket
            else {
                // Create a temporary string to store the
                // substring within the corresponding
                // opening bracket.
                string temp = "";
                while (result.Length > 0
                       && result[result.Length - 1]
                              != '[') {
                    temp = result[result.Length - 1] + temp;
                    result = result.Substring(
                        0, result.Length - 1);
                }

                // Remove the opening bracket from the
                // result string.
                result = result.Substring(0, result.Length
                                                 - 1);

                // Extract the preceding number and convert
                // it to an integer.
                string num = "";
                while (result.Length > 0
                       && Char.IsDigit(
                           result[result.Length - 1])) {
                    num = result[result.Length - 1] + num;
                    result = result.Substring(
                        0, result.Length - 1);
                }
                int int_num = int.Parse(num);

                // Append the substring to the result
                // string, repeat it to the required number
                // of times.
                for (int j = 0; j < int_num; j++) {
                    result += temp;
                }
            }
        }

        // Return the decoded string.
        return result;
    }

    // Driver code
    static void Main()
    {
        string str = "3[b2[ca]]";
        Console.WriteLine(DecodeString(str));
    }
}

// This code is contributed by Susobhan Akhuli
Javascript
// Function to decode given encoded string
function decodeString(s) {
    let result = "";

    for (let i = 0; i < s.length; i++) {
        if (s[i] !== ']') {
            // If the current character is not a closing bracket, 
            // append it to the result string.
            result += s[i];
        } else {
            // If the current character is a closing bracket:
            
            // Create a temporary string to store the substring within 
            // the corresponding opening bracket.
            let temp = "";
            while (result.length > 0 && result[result.length - 1] !== '[') {
                // Keep popping characters from the result string and add them to the 
                // temp string until we reach the opening bracket.
                temp = result[result.length - 1] + temp;
                result = result.slice(0, -1);
            }

            result = result.slice(0, -1); // Remove the opening bracket

            // Extract the preceding number and convert it to an integer.
            let num = "";
            while (result.length > 0 && !isNaN(result[result.length - 1])) {
                // Keep popping characters from the result string and add them to 
                // num string 
                // until we encounter a non-digit character.
                num = result[result.length - 1] + num;
                result = result.slice(0, -1);
            }
            let int_num = parseInt(num);

            // Append the substring to the result string, 
            // repeat it to the required number of times.
            while (int_num--) {
                result += temp;
            }
        }
    }

    // Return the decoded string.
    return result;
}

// Driver code to test above function
let str = "3[b2[ca]]";
console.log(decodeString(str)); // Output: "bcacabcacabca"
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL

Output
bcacabcacabcaca

Time Complexity: O(n), where n is the length of the input string, as we traverse the input string character by character only once.
Auxiliary Space: O(n), as we are creating a temporary string and a number string.



Previous Article
Next Article

Similar Reads

Decode a string recursively encoded as count followed by substring | Set 2 (using Recursion)
An encoded string str is given. The pattern in which the string is encoded is as follows. &lt;count&gt;[sub_str] ==&gt; The substring 'sub_str' appears count times. The task is to decode this string str. Examples: Input: str = "1[b]"Output: bExplanation: The substring 'b' is repeated 1 time. Input: str = "2[ab]"Output: ababExplanation: The substrin
9 min read
Decode an Encoded Base 64 String to ASCII String
Prerequisite : What is base64 Encoding and why we encode strings to base64 formatBase64 encoding is performed at sending node before transmitting bits over a network, and receiving node decodes that encoded data back to original ASCII string. Base64 character set is // 64 characterschar_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012
17 min read
Decode the string encoded with the given algorithm
Given a decoded string str which was decoded with the following encoding algorithm: Write down the middle character of the string then delete it and repeat the process until there are no characters left. For example, "abba" will be encoded as "bbaa". Note that the middle character is the first character of the two middle characters when the length
7 min read
Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
Given binary string str of length N​​​​, the task is to find the minimum number of characters required to be deleted from the given binary string to make a substring of 0s followed by a substring of 1s. Examples: Input: str = "00101101"Output: 2Explanation: Removing str[2] and str[6] or removing str[3] and str[6] modifies the given binary string to
11 min read
String formed with middle character of every right substring followed by left sequentially
Given a string str of length N, the task is to decrypt it using a given set of decryption rules and print the decrypted string. The decryption rules are as follows: Start with the middle character of the string str and print it.Repetitively traverse the right substring and print its middle character.Repeat the same procedure for the left substring
5 min read
Check if a string consisting only of a, b, c can be made empty by removing substring "abc" recursively
Given a string S size of N consisting of characters 'a', 'b', and 'c' only, the task is to check if the given string can be made empty by removing the string "abc" recursively or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = abcabcOutput: YesExplanation:Below are the operations performed to empty the string
7 min read
Decrypt the encoded string with help of Matrix as per given encryption decryption technique
Given an encoded (or encrypted) string S of length N, an integer M. The task is to decrypt the encrypted string and print it. The encryption and decryption techniques are given as: Encryption: The original string is placed in a Matrix of M rows and N/M columns, such that the first character of the Original text or string is placed on the top-left c
6 min read
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. Examples: Input: str = ab*c*dOutput: "ababcababcd"Explanation: For the firs
4 min read
Decode a median string to the original string
Given a string s written in median form, change it back to the original string. The median letter in a string is the letter that is in the middle of the string. If the string’s length is even, the median letter is the left of the two middle letters. The given string is formed by writing down the median letter of the word, then deleting it and repea
7 min read
Count of ways to empty given String by recursively removing all adjacent duplicates
Given a string S, in one move it is allowed to remove two adjacent equal characters. After the removal, both endpoints of the removed characters are joined. Calculate the total number of ways to empty the string. Example: Input: S = aabccbOutput: 3Explanation:1. aabccb -&gt; aabb -&gt; aa 2. aabccb -&gt; aabb -&gt; bb3. aabccb -&gt; bccb -&gt; bbHe
10 min read
Article Tags :