Type the Question

Saturday, February 16, 2019

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

No comments:

Post a Comment

Question Name:TOWER OF HANOI

#include < bits / stdc ++. h > #define lli long long using namespace std ; lli dp [ 202 ]; int main () { int t , n ; ...