Question Name:Decode the string

#include <iostream>
#include <stack>

using namespace std;

string fun(string str)
{
    // cout<<str<<endl;
    int n=str.size();
    stack<char>st;
    string ans="";
    int i=0;
    while(isalpha(str[i]) and i<n) 
    {
        ans+=str[i];
        i++;
    }
    if(i==n) return ans;
    int x=0;
    while(isdigit(str[i]))
    {
        x=x*10 + str[i]-'0';
        i++;
    }
    st.push(str[i]);
    string s="";
    i++;
    while(!st.empty() and i<n)
    {
        if(str[i]=='[') 
        {
            st.push(str[i]);
        }
        else if(str[i]==']') 
        {
            st.pop();
        }
        if(!st.empty()) s+=str[i];
        i++;
    }
    s=fun(s);
    while(x--) ans.append(s);
    // i++;
    if(i<n)
    {
        string sub=str.substr(i);
        ans.append(fun(sub));
    }
    return ans;
}

int main() {
	int t;
	cin>>t;
	while(t--)
	{
	    string str;
	    cin>>str;
	    cout<<fun(str)<<endl;
	}
	return 0;
}

Problem Description

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

  • Test Case 1

    Input (stdin)

    2
    1[b]
    3[b2[ca]]
    

    Expected Output

    b
    bcacabcacabcaca
  • Test Case 2

    Input (stdin)

    2
    2[a]
    2[c1[bc]]
    

    Expected Output

    aa
    cbccbc

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.